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

當(dāng)用python3做爬蟲的時(shí)候,一些網(wǎng)站為了防爬蟲會(huì)設(shè)置一些檢查機(jī)制,這時(shí)我們就需要添加請求頭,偽裝成瀏覽器正常訪問。
header的內(nèi)容在瀏覽器的開發(fā)者工具中便可看到,將這些信息添加到我們的爬蟲代碼中即可。
‘Accept-Encoding’:是瀏覽器發(fā)給服務(wù)器,聲明瀏覽器支持的編碼類型。一般有g(shù)zip,deflate,br 等等。
python3中的 requests包中response.text 和 response.content

response.content #字節(jié)方式的響應(yīng)體,會(huì)自動(dòng)為你解碼 gzip 和 deflate 壓縮 類型:bytes
reponse.text #字符串方式的響應(yīng)體,會(huì)自動(dòng)根據(jù)響應(yīng)頭部的字符編碼進(jìn)行解碼。類型:str

但是這里是默認(rèn)是不支持解碼br的?。。?!

br 指的是 Brotli,是一種全新的數(shù)據(jù)格式,無損壓縮,壓縮比極高(比gzip高的)
Brotli具體介紹:https://www.cnblogs.com/Leo_wl/p/9170390.html
Brotli優(yōu)勢:https://www.cnblogs.com/upyun/p/7871959.html


這個(gè)不是本文的重點(diǎn),重點(diǎn)是python3爬蟲是如何解決。


第一種:將‘Accept-Encoding’中的:br 去除
這樣接受的網(wǎng)頁頁面就是沒有壓縮的或者是默認(rèn)可解析的了。
但是我認(rèn)為,不好,人家搞出這么牛逼的算法還是要用一下的。


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

下面是爬取智聯(lián)招聘的網(wǎng)站的


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


def get_one_page(city, keyword, page):
   '''
   獲取網(wǎng)頁html內(nèi)容并返回
   '''
   paras = {
       'jl': city,         # 搜索城市
       'kw': keyword,      # 搜索關(guān)鍵詞
       'isadv': 0,         # 是否打開更詳細(xì)搜索選項(xiàng)
       'isfilter': 1,      # 是否對結(jié)果過濾
       'p': page,          # 頁數(shù)
       # 're': region        # region的縮寫,地區(qū),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:
       # 獲取網(wǎng)頁內(nèi)容,返回html數(shù)據(jù)
       response = requests.get(url, headers=headers)
       # 通過狀態(tài)碼判斷是否獲取成功
       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)

部分結(jié)果:

{'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>
<html>
<head>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>北京python招聘(求職)python招聘(求職)盡在智聯(lián)招聘</title>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="description" content="智聯(lián)招聘為您提供北京招聘信息,與北京相關(guān)的工作盡在智聯(lián)招聘" />
<meta name="keywords" content="北京招聘,北京招聘信息" />

<link rel="stylesheet" ><link rel="stylesheet" >

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

下面改一下Accept-Encoding添加br

...同上
'Accept-Encoding': 'br,gizp,defale',
...同上

部分結(jié)果:

{'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>
<html>
<head>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>北京python招聘(求職)python招聘(求職)盡在智聯(lián)招聘</title>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<meta name="description" content="智聯(lián)招聘為您提供北京招聘信息,與北京相關(guān)的工作盡在智聯(lián)招聘" />
<meta name="keywords" content="北京招聘,北京招聘信息" />

當(dāng)網(wǎng)站使用了br壓縮的話,他會(huì)告訴我們的,就是‘Content-Encoding’的值。

重點(diǎn)是

           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)

好的 這就解決了。


不得不說網(wǎng)上對于brotli的中文介紹并不算太多。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容