How do you select choices in a form using Python?

…衆ロ難τιáo~ 提交于 2019-12-02 20:50:38
senderle

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

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']

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

When you say the page has multiple forms, do you mean there are multiple <form> elements on the page, or multiple form fields (like <select>)?

The Mechanize docs for python sketch out how to select list items. Here's the sample they provide:

# Controls that represent lists (checkbox, select and radio lists) are
# ListControl instances.  Their values are sequences of list item names.
# They come in two flavours: single- and multiple-selection:
form["favorite_cheese"] = ["brie"]  # single

In your case, the code to select Value1 would look like this:

form["FORM1"] = ["Value1"]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!