python3 requests 爬虫请求头解决gzip, deflate, br中文乱码问题


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

 

本文地址:  http://www.chenxm.cc/article/1127.html
版权声明: 本文为原创文章,版权归   陈新明  所有,欢迎分享本文,转载请保留出处!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM