Entering username & password automatically using urllib.urlopen

Ryan Ginstrom software at ginstrom.com
Mon Oct 15 05:33:59 CEST 2007

> On Behalf Of rodrigo
> I am trying to retrieve a password protected page using:
> get = urllib.urlopen('http://password.protected.url"').read()

I would suggest looking at mechanize.

from mechanize import Browser

USERNAME = "user"
PASSWORD = "secret"
LOGIN_PAGE = "http://password.protected.url/"

browser = Browser()
browser.open( LOGIN_PAGE )

# log in
browser.select_form( nr=0 ) # Assuming log in form is first form on the page
# Check the form for the actual field names...
browser['user'] = USERNAME
browser['pass'] = PASSWORD

# Content goodness follows...

Of course, this assumes that the site doesn't use some kind of JavaScript
trickery to prevent automation like the above. In that case, you'd have to
use something like PAMIE

Ryan Ginstrom

More information about the Python-list mailing list