使用Python mechaniz的表单中的select选项出现ItemNotFoundError

2024-04-24 00:03:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是表格:

<p><label for="version_id">Version</label>
<select id="version_id" name="version_id"><option></option>
<option value="value1">2.1.1</option>
<option value="value2">2.1.2</option>
<option value="value3">2.1.3</option>
<option value="value4">2.1.4</option></select></p>

我的python代码:

^{pr2}$

错误消息:

File "build/bdist.macosx-10.7-intel/egg/mechanize/_form.py", line 2782, in __setitem__
File "build/bdist.macosx-10.7-intel/egg/mechanize/_form.py", line 1977, in __setattr__
File "build/bdist.macosx-10.7-intel/egg/mechanize/_form.py", line 1998, in _set_value
File "build/bdist.macosx-10.7-intel/egg/mechanize/_form.py", line 2021, in _single_set_value
File "build/bdist.macosx-10.7-intel/egg/mechanize/_form.py", line 2006, in _get_items
mechanize._form.ItemNotFoundError: insufficient items with name '2.1.2'

我的脚本只知道“2.1.2”变量,如何使用“2.1.2”而不是“value2”来设置选择值?在


Tags: inpybuildformidvalueeggversion
2条回答

稍微看一下API,我想您可以使用set_value_by_label

>>> br.form.set_value(['value2'], name='version_id')
>>> br.form.set_value_by_label(['2.1.2'], name='version_id')
>>> br.form['version_id']
['value2']
>>> br.form.get_value('version_id')
['value2']
>>> br.form.get_value_by_label('version_id')
['2.1.2']

我想你可以通过分析表格来达到目的。我做了一个快速搜索,找到一个网页上有一个html下拉框的网站,所以你可以直接尝试下面的例子。在

>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open("http://www.htmlcodetutorial.com/linking/linking_famsupp_114.html")
<response_seek_wrapper at 0x2b4b238 (...)>
>>> _, f = br.forms()                      # Select second form
>>> c = f.find_control('gourl')            # Select dropdown control
>>> c.set_value_by_label(['Idocs.com'])    # Select the item with this label

如果您随后查看所选状态,则它似乎处于选中状态:

^{pr2}$

相关问题 更多 >