以下是一些帮助您入门的基本用法示例:
>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open('http://www.w3schools.com/html/html_forms.asp')
表格有一个name
属性;有时它是空的:
>>> [f.name for f in br.forms()]
['searchform', None, None, None, None, 'input0']
表单具有一系列控件;控件也有名称:
>>> forms = [f for f in br.forms()]
>>> forms[1].controls[0].name
'firstname'
>>> [c.name for c in forms[3].controls]
['sex']
您可以获得控件中的项目列表:
>>> 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'>]
对于单选按钮,您必须进行单一选择:
>>> forms[3]['sex'] = ['male']
但选择必须在列表中:
>>> 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
对于复选框,您可以进行多项选择:
>>> [(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']
您可以找到更多信息here http://wwwsearch.sourceforge.net/mechanize/forms.html(链接盗自马特·亨佩尔 https://stackoverflow.com/questions/6359817/how-do-you-select-choices-in-a-form-using-python/6360068#6360068 :).