1. 程式人生 > >python3爬蟲中文亂碼之請求頭‘Accept-Encoding’:br 的問題

python3爬蟲中文亂碼之請求頭‘Accept-Encoding’:br 的問題

當用python3做爬蟲的時候,一些網站為了防爬蟲會設定一些檢查機制,這時我們就需要新增請求頭,偽裝成瀏覽器正常訪問。
header的內容在瀏覽器的開發者工具中便可看到,將這些資訊新增到我們的爬蟲程式碼中即可。
‘Accept-Encoding’:是瀏覽器發給伺服器,宣告瀏覽器支援的編碼型別。一般有gzip,deflate,br 等等。
python3中的 requests包中response.text 和 response.content

response.content #位元組方式的響應體,會自動為你解碼 gzip 和 deflate 壓縮 型別:bytes
reponse.text #字串方式的響應體,會自動根據響應頭部的字元編碼進行解碼。型別:str

但是這裡是預設是不支援解碼br的!!!!

br 指的是 Brotli,是一種全新的資料格式,無失真壓縮,壓縮比極高(比gzip高的)
Brotli具體介紹:https://www.cnblogs.com/Leo_wl/p/9170390.html
Brotli優勢:https://www.cnblogs.com/upyun/p/7871959.html

這個不是本文的重點,重點是python3爬蟲是如何解決。

第一種:將‘Accept-Encoding’中的:br 去除
這樣接受的網頁頁面就是沒有壓縮的或者是預設可解析的了。
但是我認為,不好,人家搞出這麼牛逼的演算法還是要用一下的。

第二種:將使用br壓縮的頁面解析。
python3 中要匯入 brotl 包 這個要自己安裝(這裡就不介紹了,百度一堆)

下面是爬取智聯招聘的網站的

from bs4 import BeautifulSoup
import requests
import brotli
from requests.exceptions import RequestException

def get_one_page(city, keyword, page):
'''
獲取網頁html內容並返回
'''
paras = {
'jl': city, # 搜尋城市
'kw': keyword, # 搜尋關鍵詞
'isadv': 0, # 是否開啟更詳細搜尋選項
'isfilter': 1, # 是否對結果過濾
'p': page, # 頁數
# 're': region # region的縮寫,地區,2005代表海淀
}

headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',
'Host': 'sou.zhaopin.com',
'Referer': 'https://www.zhaopin.com/',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8',
'Accept-Encoding': 'gizp,defale',
'Accept-Language': 'zh-CN,zh;q=0.9'
}
import chardet
url = 'https://sou.zhaopin.com/jobs/searchresult.ashx?jl={}&kw={}&sm=0&p={}'.format(paras['jl'],paras['kw'],paras['p'])
try:
# 獲取網頁內容,返回html資料
response = requests.get(url, headers=headers)
# 通過狀態碼判斷是否獲取成功
if response.status_code == 200:
#response.encoding = 'utf-8'
print(response.headers)
print(response.encoding)
key = 'Content-Encoding'
# print(response.headers[key])
print("-----------")
if(key in response.headers and response.headers['Content-Encoding'] == 'br'):
data = brotli.decompress(response.content)
data1 = data.decode('utf-8')
print(data1)
return data1
print(response.text)
return response.text
return None
except RequestException as e:
return None

def main(city, keyword, pages):

for i in range(pages):
    html = get_one_page(city, keyword, i)

if name == 'main':
main('北京', 'python', 1)

部分結果:

{'Server': 'openresty', 'Date': 'Sun, 19 Aug 2018 13:15:46 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': '361146', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding, Accept-Encoding', 'zp-trace-id': '8437455ebb5342a59f8af78ddaab1985', 'Set-Cookie': 'ZP-ENV-FLAG=gray'}
utf-8
-----------
<!DOCTYPE html>









這是沒有加br在請求的頭裡的

下面改一下Accept-Encoding新增br

...同上
'Accept-Encoding': 'br,gizp,defale',
...同上
部分結果:

{'Server': 'openresty', 'Date': 'Sun, 19 Aug 2018 13:19:02 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Vary': 'Accept-Encoding', 'zp-trace-id': '842e66a58bb2464296121c9de59a9965', 'Content-Encoding': 'br', 'Set-Cookie': 'ZP-ENV-FLAG=gray'}
utf-8
-----------
<!DOCTYPE html>









當網站使用了br壓縮的話,他會告訴我們的,就是‘Content-Encoding’的值。

重點是

       key = 'Content-Encoding'
       if(key in response.headers and response.headers['Content-Encoding'] == 'br'):
           data = brotli.decompress(response.content)
           data1 = data.decode('utf-8')
           print(data1)

好的 這就解決了。

不得不說網上對於brotli的中文介紹並不算太多。

作者:思維不混亂
連結:https://www.jianshu.com/p/70c3994efcd8
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。