日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python - 爬蟲中文亂碼之請求頭 Accept-Encoding

系統(tǒng) 1906 0
原文鏈接: https://www.jianshu.com/p/70c3994efcd8?utm_source=oschina-app

當(dāng)用 Python3 做爬蟲的時(shí)候,一些網(wǎng)站為了防爬蟲會(huì)設(shè)置一些檢查機(jī)制,這時(shí)我們就需要添加請求頭,偽裝成瀏覽器正常訪問。

header的內(nèi)容在瀏覽器的開發(fā)者工具中便可看到,將這些信息添加到我們的爬蟲代碼中即可。

Accept-Encoding:是瀏覽器發(fā)給服務(wù)器,聲明瀏覽器支持的編碼類型。一般有 gzip,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

Ps:這個(gè)不是本文的重點(diǎn),重點(diǎn)是 Python3 爬蟲是如何解決中文亂碼問題。

?

第一種

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

?

第二種

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

            
              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
-----------




              
              
              
                北京python招聘(求職)python招聘(求職)盡在智聯(lián)招聘
              
              
              
              
              
              
              
            
          

這是沒有加 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
-----------




              
              
              
                北京python招聘(求職)python招聘(求職)盡在智聯(lián)招聘
              
              
              
              
              
            
          

當(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)
            
          

好的,這就解決了!

Ps:不得不說網(wǎng)上對于 brotli 的中文介紹并不算太多,包括對 Java 爬蟲的支持教程也很少。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會(huì)非常 感謝您的哦?。。?/p>

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 柘城县| 增城市| 收藏| 西贡区| 万盛区| 文水县| 闻喜县| 高安市| 新郑市| 张家港市| 成武县| 宜丰县| 建水县| 四会市| 定襄县| 天水市| 堆龙德庆县| 古浪县| 海淀区| 巴楚县| 赣榆县| 福泉市| 寿阳县| 武穴市| 澄城县| 基隆市| 乌什县| 新河县| 广德县| 临桂县| 沂源县| 福建省| 衢州市| 青海省| 剑川县| 玉溪市| 怀化市| 开原市| 图们市| 正定县| 合江县|