Reputation: 8824
I just started experimenting with submitting webforms through mechanize. On this webpage there is a list of items to select from, MASTER_MODS
. These can be selected in either MODS
using a butten add_MODS
or in IT_MODS
using a button add_IT_MODS
(see figure at the bottom). In the form it looks like this (code for form at bottom):
<<SNIP>>
<SelectControl(MODS=[*--- none selected ---])>
<IgnoreControl(add_MODS=<None>)>
<SelectControl(MASTER_MODS=[])>
<SelectControl(IT_MODS=[*--- none selected ---])>
<IgnoreControl(remove_IT_MODS=<None>)>
<IgnoreControl(add_IT_MODS=<None>)>
<<SNIP>>
So I want to add to <SelectControl(MODS=[*--- none selected ---])>
and <SelectControl(IT_MODS=[*--- none selected ---])>
. However, when I try to add an item directly with
br.form[ 'MODS'] = ['Acetyl (N-term)']
I get mechanize._form.ItemNotFoundError: insufficient items with name 'Acetyl (N-term)'
And when I try
br.form[ 'add_MODS'] = 'Acetyl (N-term)'
I get ValueError: control 'add_MODS' is ignored, hence read-only
.
How can I add items to MODS
and IT_MODS
?
Figure and code
Code:
from mechanize import Browser, _http
br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = "http://www.matrixscience.com/cgi/search_form.pl?FORMVER=2&SEARCH=MIS"
br.select_form( 'mainSearch' )
br.open(url)
print br.form
Upvotes: 3
Views: 1269
Reputation: 7545
Try this? Explanation in the comments.
from mechanize import Browser, Item
br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)'
' Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = 'http://www.matrixscience.com'\
'/cgi/search_form.pl?FORMVER=2&SEARCH=MIS'
br.open(url)
br.select_form('mainSearch')
# get the actual control object instead of its contents
mods = br.find_control('MODS')
# add an item
item = Item(mods, {"contents": "Acetyl (N-term)", "value": "Acetyl (N-term)"})
# select it. if you don't, it doesn't appear in the output
# this is probably why MASTER_MODS appears empty
item.selected = True
print br['MODS']
# outputs: ['Acetyl (N-term)']
Assuming this works, I got it from the comments in the docs:
To add items to a list container, instantiate an Item with its control and attributes: Note that you are responsible for getting the attributes correct here, and these are not quite identical to the original HTML, due to defaulting rules and a few special attributes (e.g. Items that represent OPTIONs have a special "contents" key in their .attrs dict). In future there will be an explicitly supported way of using the parsing logic to add items and controls from HTML strings without knowing these details.
mechanize.Item(cheeses, {"contents": "mascarpone", "value": "mascarpone"})
Upvotes: 3