我正在尝试在网站 (http://www.proxy-listen.de/Proxy/Proxyliste.html) 上获取表单的控件信息。(其实我是想填表,提交,得到代理服务器列表)。我正在使用此代码来读取表单元素:
for control in br.form.controls:
if not control.name:
print " - (type) =", (control.type)
continue
print " - (name, type, value) =", (control.name, control.type, br[control.name])
出于某种原因,mechanize 没有列出单选按钮(即“type”和“liststyle”,我通过源代码发现的),因此当我提交表单时,我神秘地回到了主页(http://www.代理-listen.de)。这是我的完整代码:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import mechanize
br = mechanize.Browser()
br.addheaders = [("Content-type", "text/html, charset=utf-8")]
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 5.2; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11')]
br.set_handle_robots(False)
url = 'http://www.proxy-listen.de/Proxy/Proxyliste.html'
br.open(url)
response1 = br.response()
print response1
## Show me the forms of the website!
for form in br.forms():
print form
## Select form Nr 0, as this is the one and only form I am looking for
br.select_form(nr=0)
br.form.set_all_readonly(False)
## Fill the form
br.form['filter_country'] = ['DE']
br.form['filter_http_anon'] = ['3']
br.form['filter_http_gateway'] = ['']
br.form['filter_port'] = ['']
br.form['filter_response_time_http'] = ['1']
br.form['filter_timeouts1'] = ['10']
br.form['proxies'] = ['300']
## I already tried adding two radio buttons manually, but even this doesnt help!
'''
br.form.new_control('radio','liststyle',{'value': ['info', 'leech']})
br.form.new_control('radio','type',{'value':['http', 'https', 'socks4', 'socks5']})
br.form.fixup()
br.form['liststyle'] = ['leech']
br.form['type'] = ['http']
'''
## just to double-check the values, loop through controls!
for control in br.form.controls:
if not control.name:
print " - (type) =", (control.type)
continue
print " - (name, type, value) =", (control.name, control.type, br[control.name])
resp2 = br.submit()
page = resp2.read()
print page
我已经用萤火虫检查了与 POST 请求一起发送的变量,单选按钮并不奇怪地是 POST 请求的一部分。
任何指针都非常感谢!非常感谢。