Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login to website using python

I am trying to login to this page using Python.

I tried using the steps described on this other Stack Overflow post, and got the following code:

import urllib, urllib2, cookielib

username = 'username'
password = 'password'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://friends.cisv.org/index.cfm', login_data)
resp = opener.open('http://friends.cisv.org/index.cfm?fuseaction=activities.list')
print resp.read()

but that gave me the following output:

<SCRIPT LANGUAGE="JavaScript">
    alert('Sorry.  You need to log back in to continue. You will be returned to the home page when you click on OK.');
    document.location.href='index.cfm';
</SCRIPT>

What am I doing wrong?

like image 823
iomartin Avatar asked Nov 29 '11 19:11

iomartin


People also ask

Can you use Python to interact with websites?

The technique of automating the web with Python works great for many tasks, both general and in my field of data science. For example, we could use selenium to automatically download new data files every day (assuming the website doesn't have an API).

How do I create a login script in Python?

The Python script is as follows: print "Login Script" import getpass CorrectUsername = "Test" CorrectPassword = "TestPW" loop = 'true' while (loop == 'true'): username = raw_input("Please enter your username: ") if (username == CorrectUsername): loop1 = 'true' while (loop1 == 'true'): password = getpass.


1 Answers

I would recommend using the wonderful requests module.

The code below will get you logged into the site and persist the cookies for the duration of the session.

import requests
import sys

EMAIL = ''
PASSWORD = ''

URL = 'http://friends.cisv.org'

def main():
    # Start a session so we can have persistant cookies
    session = requests.session(config={'verbose': sys.stderr})

    # This is the form data that the page sends when logging in
    login_data = {
        'loginemail': EMAIL,
        'loginpswd': PASSWORD,
        'submit': 'login',
    }

    # Authenticate
    r = session.post(URL, data=login_data)

    # Try accessing a page that requires you to be logged in
    r = session.get('http://friends.cisv.org/index.cfm?fuseaction=user.fullprofile')

if __name__ == '__main__':
    main()
like image 190
Acorn Avatar answered Sep 29 '22 21:09

Acorn