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

<link rel="stylesheet" href="//desktop-bucket.zhaopin.cn/vendors.61c4a5.css"><link rel="stylesheet" href="//desktop-bucket.zhaopin.cn/index.d26042.css">

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

 

當網站使用了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://blog.csdn.net/weixin_40414337/article/details/88561066


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM