Python模擬登陸(使用requests庫)

之前使用 Python自帶urllib2庫做了一個簡單的模擬登陸 人人網 的功能。發現很多網站都比人人網的登陸流程複雜的多,需要好好抓包研究每一步請求過程及需要的Cookie,urllib2的cookie處理器就有點相形見絀了。很多都需要自己實現。

而由於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()



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章