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.
Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s