python爬虫br gzip default 压缩引起中文乱码

使用python3做爬虫的时候,一些网站为了防爬虫会在请求头设置一些检查机制,因此我们就需要添加请求头,伪装成浏览器正常访问。

字段情况,详见下表:
请求头字段 说明 响应头字段
Accept 告知服务器发送何种媒体类型 Content-Type
Accept-Language 告知服务器发送何种语言 Content-Language
Accept-Charset 告知服务器发送何种字符集 Content-Type
Accept-Encoding 告知服务器采用何种压缩方式 Content-Encoding
“Accept-Encoding”:是浏览器发给服务器,声明浏览器支持的编码类型。一般有gzip,deflate,br 等等。

假设客户端发送以下信息:

1
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
1
Accept-Encoding = “gzip, deflate”
第二种:使用编码类型:br进行页面解析
安装
1
pip install Brotli
使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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运行时会提示错误:

1
brotli.error: BrotliDecompress failed

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值