如何使用Python选择表单中的选项? [英] How do you select choices in a form using Python?

查看:331
本文介绍了如何使用Python选择表单中的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何以格式设置的方式选择选项

I'd like to know how to select options in a form that is formatted like

  <td align="left">
                  <select name="FORM1" id="FORM1" multiple="multiple" size="5">
                      <option value="Value1">Value1</option>
                      <option value="Value2">Value2</option>
                  </select>
  </td>

现在,我正在使用机械化连接到该网站并遍历所需的页面.该页面具有许多形式,例如FORM1,FORM2,FORM3等,并带有选项.我想选择(启用)Value1,然后告诉机械化实例点击提交"按钮.哪种方法可以快速启用基于表单名称的选项?

Right now, I am using mechanize to connect to the website and traverse to the desired page. This page has many forms such as FORM1, FORM2, FORM3, etc. with options. I'd like to select (enable) Value1 then tell the instance of mechanize to hit the submit button. Which would be a quick way to enable an option based on the form name?

推荐答案

以下是一些基本用法示例,可以帮助您入门:

Here are some basic usage examples to get you going:

>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open('http://www.w3schools.com/html/html_forms.asp')

表单具有name属性;有时却是空的:

Forms have a name attribute; sometimes it's empty though:

>>> [f.name for f in br.forms()]
['searchform', None, None, None, None, 'input0']

表单具有一系列控件;控件也有名称:

Forms have a sequence of controls; controls also have names:

>>> forms = [f for f in br.forms()]
>>> forms[1].controls[0].name
'firstname'
>>> [c.name for c in forms[3].controls]
['sex']

您可以在控件中获得项目列表:

You can get a listing of items in a control:

>>> forms[3].controls[0].get_items()
[<Item name='male' id=None type='radio' name='sex' value='male'>, <Item name='female' id=None type='radio' name='sex' value='female'>]

对于单选按钮,您必须进行一次选择:

For radio buttons, you have to make a single selection:

>>> forms[3]['sex'] = ['male']

但是选择必须在列表中:

But the selection has to be in a list:

>>> forms[3]['sex'] = 'male'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 2782, in __setitem__
    control.value = value
  File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 1977, in __setattr__
    self._set_value(value)
  File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 1985, in _set_value
    raise TypeError("ListControl, must set a sequence")
TypeError: ListControl, must set a sequence

对于复选框,您可以进行多项选择:

For check boxes you can make multiple selections:

>>> [(c.name, c.get_items()) for c in forms[4].controls]
[('vehicle', [<Item name='Bike' id=None type='checkbox' name='vehicle' value='Bike'>, <Item name='Car' id=None type='checkbox' name='vehicle' value='Car'>])]
>>> forms[4]['vehicle'] = ['Bike', 'Car']

您可以在此处(从Mat Hempel :).

You can find more info here (link stolen from Matt Hempel :).

这篇关于如何使用Python选择表单中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆