gpt4 book ai didi

python - 如何使用 Python 在表单中选择选项?

转载 作者:太空狗 更新时间:2023-10-29 18:16:32 24 4
gpt4 key购买 nike

我想知道如何在格式如下的表单中选择选项

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

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

最佳答案

这里有一些基本的用法示例,可以帮助您入门:

>>> 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 (链接从 Matt Hempel 窃取:)。

关于python - 如何使用 Python 在表单中选择选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6359817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com