Simulate login using cookielib in Python
- 2020-05-07 20:00:36
- OfStack
The previous briefly mentioned Python simulation login program, but did not write clearly, here is a annotated Python simulation login sample program. In short, the following process is as follows: first obtain cookie with cookielib, then enter the website that needs to be logged in with cookie.
# -*- coding: utf-8 -*-
# !/usr/bin/python
import urllib2
import urllib
import cookielib
import re
auth_url = 'http://www.nowamagic.net/'
home_url = 'http://www.nowamagic.net/';
# Login username and password
data={
"username":"nowamagic",
"password":"pass"
}
# urllib coding
post_data=urllib.urlencode(data)
# Sending header information
headers ={
"Host":"www.nowamagic.net",
"Referer": "http://www.nowamagic.net"
}
# Initialize the 1 a CookieJar To deal with Cookie
cookieJar=cookielib.CookieJar()
# instantiation 1 A global opener
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
# To obtain cookie
req=urllib2.Request(auth_url,post_data,headers)
result = opener.open(req)
# Visit the home page Automatically with the cookie information
result = opener.open(home_url)
# According to the results
print result.read()
A few sample programs are attached:
1. Use the existing cookie to access the website
import cookielib, urllib2
ckjar = cookielib.MozillaCookieJar(os.path.join('C:\Documents and Settings\tom\Application Data\Mozilla\Firefox\Profiles\h5m61j1i.default', 'cookies.txt'))
req = urllib2.Request(url, postdata, header)
req.add_header('User-Agent', \
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ckjar) )
f = opener.open(req)
htm = f.read()
f.close()
2. Visit the website to obtain cookie and save the cookie in the cookie file
import cookielib, urllib2
req = urllib2.Request(url, postdata, header)
req.add_header('User-Agent', \
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')
ckjar = cookielib.MozillaCookieJar(filename)
ckproc = urllib2.HTTPCookieProcessor(ckjar)
opener = urllib2.build_opener(ckproc)
f = opener.open(req)
htm = f.read()
f.close()
ckjar.save(ignore_discard=True, ignore_expires=True)
3. Generate cookie with the specified parameters and use this cookie to access the website
import cookielib, urllib2
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
values = {'redirect':", 'email':'abc@abc.com',
'password':'password', 'rememberme':", 'submit':'OK, Let Me In!'}
data = urllib.urlencode(values)
request = urllib2.Request(url, data)
url = urlOpener.open(request)
print url.info()
page = url.read()
request = urllib2.Request(url)
url = urlOpener.open(request)
page = url.read()
print page