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?
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).
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With