Tuesday, October 12, 2010

fun with python mechanize

In the Perl world, there is WWW-mechanize module which is used as a web browser in perl to use to get load a webpage. In python there is a mechanize module that do precisely that.

To install just:
pip install mechanize

Lets assume that we have a webapp at address http://mywebapp

here
import mechanize
page = mechanize.urlopen('http://mywebapp')
#list all the form on the page
forms = mechanize.ParseResponse(page,backwards_compat=False)
# Get the first form
form = forms[0]
# Put data into <input name='query' ....
form['query'] = 'field'
# submit it
result = mechanize.urlopen(form.click())
print result.read()
view raw gistfile1.py hosted with ❤ by GitHub

The code above shows how to open a page, fill in a form field, and submit it, and get the next page. It will print whole page in html, from the result of a query .

This is useful for automate access to a webpage, in my case, to test a webapp in the office. I also use this to do load test with the python multi mechanize. Pretty nifty as it is actually a browser itself.

No comments:

Post a Comment