如何在python中选择带有mechanize的下拉菜单项?

2024-04-28 00:04:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很困惑。我基本上是想用mechanize for 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

我和运营商有问题,这是一个下拉菜单。


Tags: brcomhttp表单for网站代码段open
2条回答

很抱歉让一篇死了很久的帖子复活,但这仍然是我在谷歌上能找到的最好的答案,它不起作用。经过比我想承认的更多的时间,我终于明白了。红外线对形状物体来说是正确的,但对其他物体却不正确,他的密码也不起作用。下面是一些对我有效的代码(尽管我确信存在一个更优雅的解决方案):

# 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

根据mechanize documentation examples,您需要访问form对象的属性,而不是browser对象的属性。另外,对于select控件,需要将值设置为列表:

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()

相关问题 更多 >