Using Python Mechanize like “Tamper Data”
Question
I'm writing a web testing script with python (2.6) and mechanize (0.1.11). The page I'm working with has an html form with a select field like this:
<select name="field1" size="1">
<option value="A" selected>A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
In mechanize, if I try something like this:
browser.form['field1'] = ['E']
Then I get an error: ClientForm.ItemNotFoundError: insufficient items with name 'E'
I can do this manually with the "Tamper Data" firefox extension. Is there a way to do this with python and mechanize? Can I somehow convince mechanize that the form actually has the value I want to submit?
Solution
After poking around with the guts of ClientForm, it looks like you can trick it into adding another item.
For a select field, something like this seems to work:
xitem = ClientForm.Item(browser.form.find_control(name="field1"),
{'contents':'E', 'value':'E', 'label':'E'})
Similarly, for a radio button control
xitem = ClientForm.Item(browser.form.find_control(name="field2"),
{'type':'radio', 'name':'field2', 'value':'X'})
Note that the Item initializer will automatically update the list of items for the specified control, so you only need to create the item properly for it to appear.