好吧,我在冒险中使用了 mechanize、requests、beautiful soup,甚至 selenium 来做这样的事情,我得出的结论是 urllib 和其他默认模块是最好的方法。唯一的问题是我根本不知道如何使用它。所以有人可以告诉我一些专门了解它的好地方吗?此外,我通过示例学习得最好,所以如果有人将其转换为我要求的内容,那就太好了(还包括提交按钮哈哈)
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.jonessoda.com/contests/back2school")
element = driver.find_element_by_name("fname")
element.send_keys("Ben")
最佳答案
您确实需要 Selenium。它模拟浏览器上的 GUI 交互。 在执行诸如输入比赛表格数据之类的操作时,这将是最不容易被发现的方式。
A note about selenium: It is not a language-specific library. There are client specific bindings for each language. Most examples and how-to's you'll see are actually written in Java.
一个很好的资源是Selenium-python
这是您的工作示例。包括提交按钮。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
i = 2 # do it 2 times
while i > 0:
driver = webdriver.Firefox()
driver.get("http://www.jonessoda.com/contests/back2school")
def find_by_xpath(locator):
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, locator))
)
return element
class FormPage(object):
def fill_form(self, data):
find_by_xpath('//input[@name = "fname"]').send_keys(data['fname'])
find_by_xpath('//input[@name = "lname"]').send_keys(data['lname'])
find_by_xpath('//input[@name = "email"]').send_keys(data['email'])
find_by_xpath('//select[@name = "birthday_month"]').send_keys(data['month'])
find_by_xpath('//select[@name = "birthday_day"]').send_keys(data['day'])
find_by_xpath('//select[@name = "birthday_year"]').send_keys(data['year'])
return self # makes it so you can call .submit() after calling this function
def submit(self):
find_by_xpath('//input[@value = "Submit"]').click()
data = {
'fname': 'Sheep',
'lname': 'Test',
'email': 'jess@sheeptest.com',
'month': 'October',
'day': '29',
'year': '1920'
}
FormPage().fill_form(data).submit()
driver.quit() # closes the webbrowser
i = i - 1
关于python - 使用内置 Python 模块填写 Web 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050075/