一、背景
相關博文:https://www.jianshu.com/p/9fce799edf1e
https://blog.csdn.net/h19910518/article/details/79348051
Cookie
HTTP協議它是無狀態的,就是說這一次請求和上一次請求是沒有任何關系的,沒有關聯的。這種無狀態的的好處是快速。但是有時我們希望幾個請求的頁面要有關聯,比如:在a已經登錄,在b也希望是登陸狀態,但是,這是2個不同的頁面,也就是2個不同的HTTP請求,這2個HTTP請求是無狀態的,也就是無關聯的,所以無法單純的在b中讀取到它在a中已經登陸了,使用數據庫可以記錄登錄狀態,但會給服務器造成壓力。
Cookie指某些網站為了辨別用戶身份,進行Session跟蹤而存儲在用戶本地終端上的數據。當你瀏覽某網站時,網站存儲在你機器上的一個小文本文件,它記錄了你的用戶ID,密碼、瀏覽過的網頁、停留的時間等信息,當你再次來到該網站時,cookie隨每個請求發送到同一服務器,服務器通過讀取Cookie,得知你的相關信息,就可以做出相應的動作。
Session
Session:在計算機中,尤其是在網絡應用中,稱為“會話控制”。Session對象存儲特定用戶會話所需的屬性及配置信息
1.客戶端發送一個 帶有Set-Cookie 屬性的請求;
2.這個請求需要由服務端用session加密算法進行加密,得到一個session_id 和 cookie 的對應字典
3.下次客戶端登錄時,瀏覽器會發送帶有Cookie頭部的請求的時候,用戶就可以不用登陸了。
存儲在Session對象的變量不會丟失,而是在整個Session中一直存在下去。當用戶請求來自應用程序的web頁時,如果該用戶還沒有Session,則Web服務器會自動創建一個Session對象。而當Session過期或被放棄的時候,服務器會終止該Session。
二、准備
1.手動登錄人人網
- 查看驗證碼類型
- 使用fiddler抓取數據(請求的url、cookie數據)
2.雲打碼平台使用
- 注冊賬號(用戶和開發者)
- 查看開發文檔
- 下載DLL
三、主要步驟
- 使用requests的get方法,獲取驗證碼圖片,保存至本地
- 將本地的驗證碼圖片上傳至雲打碼進行識別
- 將識別結果與其他數據(賬號、密碼等,通過fiddler抓取)進行封裝到data參數中
- 實例化一個Session對象,使用post方法,提交url和data參數,實現登錄。
代碼
import http.client, mimetypes, urllib, json, time, requests
from lxml import etree
from YDMHTTPDemo3.x import YDMHttp #將下載的DLL導入
#給雲打碼定義一個函數
def getVCode( username, password,filename,codeType):
appid = 'xxxx'
appkey = '3b753c7c24fba02dexxxxxxxxxxxxxxx'
filename = filename
codeType = codeType
timeout = 30
if (username == 'username'):
print('請設置好相關參數再測試')
else:
yundama = YDMHttp(username, password, appid, appkey) #實現雲打碼用戶登錄
uid = yundama.login();
print('uid: %s' % uid)
balance = yundama.balance();
print('balance: %s' % balance)
cid, result = yundama.decode(filename, codetype, timeout); #驗證碼圖片上傳,返回結果
print('cid: %s, result: %s' % (cid, result))
target1_url = "http://www.renren.com/"
headers = headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
}
response = requests.get(url = target1_url,headers = headers)
ht = response.text
tree = etree.HTML(ht)
img= tree.xpath('//img[@verifyPic_login]/@src')
#data中的參數通過手動登錄時,使用fiddler抓取。
data = {
'captcha_type':'web_login',
'domain':'renren.com',
'email':'xxxxxxxx@xxx.com', #郵箱
'f':'',
'icode':"", #驗證碼
'key_id':'1',
'origURL':'http://www.renren.com/home',
'password':'06735438342bxxxxxxxxxxxxxxxxxxxxxxxxx', #加密后的密碼
'rkey':'8a339012c2e46e9xxxxxxxxxxxxxxxxxx',
}
target2_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2019841747473'
if img: #如果有驗證碼
urllib.request.urlretrieve(img[0],'./getimage.jpg')
VCode = getVCode( 'Sroxi', 'xxx', './getimage.jpg', '1006')
print(VCode)
data['icode'] = VCode
session = requests.Session()
session.post(url=target2_url,data = data,headers = headers)
target3_url = 'http://www.renren.com/58xxxxxx'
response1 = session.get(url = target3_url,headers = headers)
htmlfile = response1.text
with open('renren.html','w',encoding = 'utf8') as f:
f.write(htmlfile)
print('finish')