2020年9月9日 17:29 220 人閱讀 0 條評論 編輯
使用python3做爬蟲的時候,一些網站為了防爬蟲會在請求頭設置一些檢查機制,因此我們就需要添加請求頭,偽裝成瀏覽器正常訪問。
字段情況,詳見下表:
請求頭字段 | 說明 | 響應頭字段 |
Accept | 告知服務器發送何種媒體類型 | Content-Type |
Accept-Language | 告知服務器發送何種語言 | Content-Language |
Accept-Charset | 告知服務器發送何種字符集 | Content-Type |
Accept-Encoding | 告知服務器采用何種壓縮方式 | Content-Encoding |
"Accept-Encoding":是瀏覽器發給服務器,聲明瀏覽器支持的編碼類型。一般有gzip,deflate,br 等等。
假設客戶端發送以下信息:
Accept-Encoding:gzip,deflate,br
表示支持采用 gzip、deflate 或 br 壓縮過的資源
而python3中的 requests只有response.text 和 response.content
-
response.content #字節方式的響應體,會自動為你解碼 gzip 和 deflate 壓縮 類型:bytes
-
reponse.text #字符串方式的響應體,會自動根據響應頭部的字符編碼進行解碼。類型:str
但是這里requests默認不支持解碼br
什么是br
br 指的是 Brotli,是一種全新的數據格式,無損壓縮,壓縮比極高(比gzip高的)
Brotli具體介紹:https://www.cnblogs.com/Leo_wl/p/9170390.html
Brotli優勢:https://www.cnblogs.com/upyun/p/7871959.html
解決方法
第一種:從Accept-Encoding中去除編碼類型:br
Accept-Encoding = "gzip, deflate"
第二種:使用編碼類型:br進行頁面解析
安裝
pip install Brotli
使用:
import brotli import requests headers = {} headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" headers['Accept-Encoding'] = "gzip, deflate, br" headers['Host'] = "book.douban.com" headers['Referer'] = "book.douban.com" headers['Sec-Fetch-Dest'] = "document" headers['Sec-Fetch-Mode'] = "navigate" headers['Upgrade-Insecure-Requests'] = "1" s=requests.Session() url="https://book.douban.com/tag/%E5%B0%8F%E8%AF%B4" try: response = s.get(url, headers=headers) except: return "" if response.status_code == 200: print(response.headers) if response.headers.get('Content-Encoding') == 'br': data = brotli.decompress(response.content) return data.decode('utf-8') else: return response.text return ""
注意:python3.8和brotli=1.0.9運行時會提示錯誤:
brotli.error: BrotliDecompress failed