下面是一些基本用法示例:>>> 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()
[, ]
对于单选按钮,必须进行单个选择:>>> forms[3]['sex'] = ['male']
但选择必须在列表中:>>> forms[3]['sex'] = 'male'
Traceback (most recent call last):
File "", line 1, in
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', [, ])]
>>> forms[4]['vehicle'] = ['Bike', 'Car']
你可以找到更多信息here(链接从Matt Hempel:)被盗。