ItemNotFoundError with select choices in a form using Python mechanize
-
25-10-2019 - |
Question
Here is the form:
<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>
My python code:
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
The error message:
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'
My script just know about the "2.1.2" var, how could I set the select value by using "2.1.2" not "value2"?
Solution
I think you can get there by parsing the form. I did a quick search to find a site with a html dropdown box on the page, so you could directly try the below example.
>>> 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
If you then look at the selected state, it seems to be selected:
>>> c.items[2]._selected
True
>>> c.set_value_by_label(['Ninth Wonder'])
>>> c.items[2]._selected
False
OTHER TIPS
Looking a little bit at the API, I think you can use 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']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow