爬蟲筆記3:requests庫使用
阿新 • • 發佈:2019-01-16
esp pri 進行 驗證 get .com 使用 quest pro
requests庫概述
Python內置的urllib庫在對於Cookies,登錄驗證,代理方面等操作太繁瑣。而requests庫在這些方面卻做得很好!
請求方法:get(),返回一個Response對象
參數:url,data,headers,proxies,verity,timeout
1、url:請求的URL
2、data:模擬表單,參數是傳一個字典
3、headers:請求頭,偽裝成瀏覽器
4、proxies:防止被封IP,參數是傳一個字典
5、timeout:超時設置
6、verify:SSL證書驗證,默認是True屬性:
text:返回Unicode內容;
content:返回字節流內容
status-code:狀態碼
cookies:返回cookies
其他重要方法:
post():使用post請求
Session():獲取會話維持
get()和post()的區別
1、 get:表單數據會附在url之後(HTTP協議頭)
post:數據不會附在url之後(HTTP包的包體中)
2、 get:對URL長度有限制
post:理論上不限制3、 get:可被緩存
post:不可被緩存(安全性高)
response對象的text和content區別
content返回的是byte型數據,而text返回的是Unicode數據
代碼演示:import requests #請求字節流文件 r = requests.get(‘https://p1.ssl.qhimg.com/t0151320b1d0fc50be8.png‘) print(r.text)#已經以某種格式進行解碼,出現亂碼 print(r.content)#返回文件的bytes數據 with open(‘360.png‘,‘wb‘) as f: f.write(r.content)
cookies獲取
使用response對象的cookies屬性獲取for key,value in r.cookies.items(): print(key,‘:‘,value)
爬蟲筆記3:requests庫使用