2011-09-24 96 views
6

我真的很困惑。我基本上是试图填写一个网站上的机械化python表单。除了下拉菜单,我还有一切工作。我用什么来选择它,以及为价值做些什么?我不知道我是否应该把选择的名称或它的数值。帮助将不胜感激,谢谢。如何使用python中的mechanize选择下拉菜单项?

代码片段:

try: 
     br.open("http://www.website.com/") 
     try: 
      br.select_form(nr=0) 
      br['number'] = "mynumber" 
      br['from'] = "[email protected]" 
      br['subject'] = "Yellow" 
      br['carrier'] = "203" 
      br['message'] = "Hello, World!" 
      response = br.submit() 
     except: 
      pass 
    except: 
     print "Couldn't connect!" 
     quit 

我遇到的载体,这是一个下拉菜单的麻烦。

+0

请给出一个具体示例。显示你尝试过的代码以及当你尝试过时发生了什么? – infrared

+0

好的,现在发布 – user962889

+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'] = "[email protected]" 
form['subject'] = "Yellow" 
form['carrier'] = ["203"] 
form['message'] = "Hello, World!" 
response = br.submit() 
+0

我不确定你是否会回复,因为我昨天问过这个问题,但是对于“运营商”,我是否会将值设置为下拉列表或值的名称?例如:名称:Foo值:129 – user962889

+0

您可以发布有问题的表单的HTML,以便我可以正确测试并回复? – infrared

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'] = "[email protected]" 
    br.form['subject'] = "Yellow" 
    br.form['message'] = "Hello, World!" 
    response = br.submit() 

    # exit the loop 
    break 
+0

您可能可以做control.disabled = False control.value = [“203”]而不是循环。让我知道 – Lazik

相关问题