Lionel
Lionel

Reputation: 3288

Python Mechanize with Dynamic Dropdown Selection

I'm using mechanize to fill forms and I run into a problem with dynamically-filled dropdown lists that are dependent on a previous selection.

In mechanize, I do something like this to select the category:

import mechanize
br = mechanize.Browser()
"""Select the form and set up the browser"""
br["state"] = ["California"]
br["city"] = ["San Francisco"] # this is where the error is
br.submit()

I cannot choose the city as "San Francisco" until I have chosen the state as "California," because the city dropdown list is dynamically populated after choosing "California."

How can I submit the city with Python and mechanize?

Upvotes: 3

Views: 1750

Answers (1)

Ryan Ginstrom
Ryan Ginstrom

Reputation: 14121

mechanize doesn't support JavaScript. Instead, you should use urllib2 to send the desired values.

import urllib2
import urllib

values = dict(state="CA", city="SF") # examine form for actual vars
try:
    req = urllib2.Request("http://example.com/post.php",
                          urllib.urlencode(values))
    response_page = urllib2.urlopen(req).read()
except urllib2.HTTPError, details:
    pass #do something with the error here...

Upvotes: 1

Related Questions