如何在Python中使用mechanize选择下拉菜单项?
我真的很困惑。我基本上是在用Python的mechanize库填写一个网站上的表单。我把其他的都弄好了,只有下拉菜单不行。我该用什么来选择它,值应该填什么?我不知道是应该填选项的名字还是它的数字值。非常感谢任何帮助!
代码片段:
try:
br.open("http://www.website.com/")
try:
br.select_form(nr=0)
br['number'] = "mynumber"
br['from'] = "herpderp@gmail.com"
br['subject'] = "Yellow"
br['carrier'] = "203"
br['message'] = "Hello, World!"
response = br.submit()
except:
pass
except:
print "Couldn't connect!"
quit
我在处理一个下拉菜单时遇到了问题,它是一个选择承运人的地方。
2 个回答
3
抱歉把一个很久以前的帖子重新提起,但这是我在谷歌上找到的最好答案,结果却不管用。在花了比我愿意承认的更多时间后,我终于搞明白了。infrared说的关于表单对象的部分是对的,但其他的就不太准确了,他的代码也不管用。这里有一些对我有效的代码(虽然我相信还有更优雅的解决方案):
# Select the form
br.open("http://www.website.com/")
br.select_form(nr=0) # you might need to change the 0 depending on the website
# find the carrier drop down menu
control = br.form.find_control("carrier")
# loop through items to find the match
for item in control.items:
if item.name == "203":
# it matches, so select it
item.selected = True
# now fill out the rest of the form and submit
br.form['number'] = "mynumber"
br.form['from'] = "herpderp@gmail.com"
br.form['subject'] = "Yellow"
br.form['message'] = "Hello, World!"
response = br.submit()
# exit the loop
break
3
根据mechanize的文档示例,你需要访问form
对象的属性,而不是browser
对象的属性。此外,对于选择控件,你需要把值设置为一个列表:
br.open("http://www.website.com/")
br.select_form(nr=0)
form = br.form
form['number'] = "mynumber"
form['from'] = "herpderp@gmail.com"
form['subject'] = "Yellow"
form['carrier'] = ["203"]
form['message'] = "Hello, World!"
response = br.submit()