automation – How can I login to a website with Python?

automation – How can I login to a website with Python?

Maybe you want to use twill. Its quite easy to use and should be able to do what you want.

It will look like the following:

from twill.commands import *

fv(1, email-email,
fv(1, password-clear, testpass)


You can use showforms() to list all forms once you used go… to browse to the site you want to login. Just try it from the python interpreter.

Let me try to make it simple, suppose URL of the site is and you need to sign up by filling username and password, so we go to the login page say now and view its source code and search for the action URL it will be in form tag something like

 <form name=loginform method=post action=userinfo.php>

now take userinfo.php to make absolute URL which will be, now run a simple python script

import requests
url =
values = {username: user,
          password: pass}

r =, data=values)
print r.content

I Hope that this helps someone somewhere someday.

automation – How can I login to a website with Python?

Typically youll need cookies to log into a site, which means cookielib, urllib and urllib2. Heres a class which I wrote back when I was playing Facebook web games:

import cookielib
import urllib
import urllib2

# set these to whatever your fb account is
fb_username = [email protected]
fb_password = secretpassword

class WebGamePlayer(object):

    def __init__(self, login, password):
         Start up... 
        self.login = login
        self.password = password

        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
        self.opener.addheaders = [
            (User-agent, (Mozilla/4.0 (compatible; MSIE 6.0; 
                           Windows NT 5.2; .NET CLR 1.1.4322)))

        # need this twice - once to set cookies, once to log in...

    def loginToFacebook(self):
        Handle login. This should populate our cookie jar.
        login_data = urllib.urlencode({
            email : self.login,
            pass : self.password,
        response =, login_data)
        return .join(response.readlines())

You wont necessarily need the HTTPS or Redirect handlers, but they dont hurt, and it makes the opener much more robust. You also might not need cookies, but its hard to tell just from the form that youve posted. I suspect that you might, purely from the Remember me input thats been commented out.

Leave a Reply

Your email address will not be published. Required fields are marked *