使用Python mechanize时,表单选择项出现ItemNotFoundError

0 投票
2 回答
1603 浏览
提问于 2025-04-17 07:18

这是表单:

<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代码:

import mechanize
br = mechanize.Browser()
br.open('http://www.example.com/html/html_forms.asp')
br["version_id"] = ["value2"] # works
br["version_id"] = ["2.1.2"] # don't work

错误信息:

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”?

2 个回答

0

我稍微看了一下这个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']
0

我觉得你可以通过解析表单来实现这个功能。我快速搜索了一下,找到了一个页面上有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

如果你查看一下选中的状态,似乎是被选中的:

>>> c.items[2]._selected
True
>>> c.set_value_by_label(['Ninth Wonder'])
>>> c.items[2]._selected
False

撰写回答