用Python模拟登录网站
前面简单提到了 Python 模拟登录的程序,但是没写清楚,这里再补上一个带注释的 Python 模拟登录的示例程序。简单说一下流程:先用cookielib获取cookie,再用获取到的cookie,进入需要登录的网站。
13 |
"username" : "nowamagic" , |
17 |
post_data = urllib.urlencode(data) |
20 |
"Host" : "www.nowamagic.net" , |
24 |
cookieJar = cookielib.CookieJar() |
26 |
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar)) |
28 |
req = urllib2.Request(auth_url,post_data,headers) |
29 |
result = opener. open (req) |
31 |
result = opener. open (home_url) |
再附带几个示例程序:
1. 使用已有的cookie访问网站
01 |
import cookielib, urllib2 |
03 |
ckjar = cookielib.MozillaCookieJar(os.path.join( 'C:\Documents and Settings\tom\Application Data\Mozilla\Firefox\Profiles\h5m61j1i.default' , 'cookies.txt' )) |
05 |
req = urllib2.Request(url, postdata, header) |
07 |
req.add_header( 'User-Agent' , \ |
08 |
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)' ) |
10 |
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ckjar) ) |
2. 访问网站获得cookie,并把获得的cookie保存在cookie文件中
01 |
import cookielib, urllib2 |
03 |
req = urllib2.Request(url, postdata, header) |
04 |
req.add_header( 'User-Agent' , \ |
05 |
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)' ) |
07 |
ckjar = cookielib.MozillaCookieJar(filename) |
08 |
ckproc = urllib2.HTTPCookieProcessor(ckjar) |
10 |
opener = urllib2.build_opener(ckproc) |
16 |
ckjar.save(ignore_discard = True , ignore_expires = True ) |
3. 使用指定的参数生成cookie,并用这个cookie访问网站
01 |
import cookielib, urllib2 |
03 |
cookiejar = cookielib.CookieJar() |
04 |
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) |
05 |
values = { 'redirect' :", 'email' : 'abc@abc.com' , |
06 |
'password' : 'password' , 'rememberme' :", 'submit' : 'OK, Let Me In!' } |
07 |
data = urllib.urlencode(values) |
09 |
request = urllib2.Request(url, data) |
10 |
url = urlOpener. open (request) |
14 |
request = urllib2.Request(url) |
15 |
url = urlOpener. open (request) |