而由於urllib2本身的使用起來不方便,所以改用第三方庫requests庫,這個庫也是使用很廣泛的一個Python庫。
當然了,每個網站的登陸流程略有不同,代碼不可能完全通用,需要自己抓包分析過程,(使用HTTPFox等),弄懂原理,然後稍作修改。
# -*- coding:utf-8 -*-
import urllib
import ssl
import requests
g_cookie = ''
def login_web():
url = 'https://www.xxx.com'
#verify和allow_redirects看需要,我這邊需要取到每一步的cookie所以禁用重定向。前面的get請求一般都是爲了獲取Cookie
resp = requests.get(url, verify=False, allow_redirects=False)
g_cookie = resp.headers['set-cookie']
get_url = url + resp.headers['location']
headers = {'Cookie':g_cookie}
resp = requests.get(get_url,headers=headers,verify=False, allow_redirects=False)
#print "resp.headers:",resp.headers
get_url = resp.headers['location']
resp = requests.get(get_url,verify=False, allow_redirects=False)
#print "===>",resp.headers
post_url = resp.headers['location']
headers = {
'Content-type':'application/x-www-form-urlencoded'
}
data = {'username':'test','password':'password','other':'other'}
#這裏纔是真正的登陸過程,data裏面是抓包獲取的賬號密碼及其他信息。
resp = requests.post(post_url, urllib.urlencode(data),
headers=headers,
verify=False,
allow_redirects=False)
get_url = resp.headers['location']
headers = {'Cookie':resp.headers['set-cookie']}
#我要登陸的網站重定向比較多,所以不停的get。
r = requests.get(get_url,headers=headers,verify=False,allow_redirects=False)
get_url = r.headers['location']
headers = {'Cookie':g_cookie} # 最開始獲得的Cookie派上用場了
resp = requests.get(get_url,headers=headers,verify=False,allow_redirects=False)
get_url = 'https://www.xxx.com'
resp = requests.get(get_url, headers=headers,verify=False,allow_redirects=False)
file = open('login_info.txt','w')
file.write(resp.content)
if __name__ == '__main__':
login_web()