使用内置 Python 模块填写 Web 表单数据 [英] Filling Out Web Form Data Using Built-In Python Modules
问题描述
好吧,所以我在冒险中使用了机械化、请求、漂亮的汤,甚至硒来做这样的事情,我得出的结论是 urllib 和其他默认模块是最好的方法.唯一的问题是我根本不知道如何使用它..所以有人可以告诉我一些专门了解它的好地方吗?此外,我通过示例学习得最好,所以如果有人将其转换为我要求的内容,那就太好了(还包括一个提交按钮,哈哈)
Alright so I have used mechanize, requests, beautiful soup, and even selenium on my venture to do something like this and I have come to the conclusion that urllib and the other default modules are the best way to go. Only problem is I can't figure out how to use it at all.. So can someone please show me some good places to learn about that specifically? Also I learn best by examples so if someone would convert this to what I am asking for that would be great (also include a submit button lol)
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 交互.在执行诸如输入比赛表格数据之类的操作时,这将是最不容易被检测到的方式.
You do want Selenium. It simulates GUI interactions on a browser. When doing things like entering competition form data, this is going to be the way that is least detectable.
关于 selenium 的说明:它不是特定于语言的库.每种语言都有特定于客户端的绑定.您将看到的大多数示例和操作方法实际上都是用 Java 编写的.
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
这是您的工作示例.包括提交按钮.
Here's your working example. Including submit button.
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 模块填写 Web 表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!