Programmatically log into a website with Python and urllib, urllib2. This one for my django.

"""
Log into Django Site
====================


By Yuji Tomita
2/22/2011
"""

import urllib
import urllib2
import contextlib


def login(login_url, username, password):
    cookies = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookies)
    urllib2.install_opener(opener)
    
    opener.open(login_url)
    
    try:
        token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0]
    except IndexError:
        return False, "no csrftoken"
    
    params = dict(username=username, password=password, \
        this_is_the_login_form=True,
        csrfmiddlewaretoken=token,
         )
    encoded_params = urllib.urlencode(params)
    
    with contextlib.closing(opener.open(login_url, encoded_params)) as f:
        html = f.read()
        
        print html
    # we're in.

1 Comment

  1. I had the same thing to do, unable to do it with curl, and someone on S.O. pointed me to twill…and it works really well, with much less lines of code

Leave a reply to Dominique Guardiola Cancel reply