如何在python中使用mechanize选择下拉菜单中的项目?

时间:2011-09-24 18:10:48

标签: python drop-down-menu mechanize

我真的很困惑。我基本上试图用机械化为python填写网站上的表格。除了下拉菜单,我得到了一切工作。我用什么来选择它以及我为该值添加了什么?我不知道我是否应该把选择的名称或它的数值。非常感谢帮助,谢谢。

代码段:

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 个答案:

答案 0 :(得分:3)

根据mechanize documentation examples,您需要访问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()

答案 1 :(得分:3)

很抱歉恢复了一篇很长的帖子,但这是我在谷歌上找到的最好的答案,它不起作用。经过比我承认的更多的时间,我想通了。红外线是关于形式对象的,但不是关于其余的,并且他的代码不起作用。这里有一些适用于我的代码(虽然我确信存在更优雅的解决方案):

# 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