python3 requests br 中文乱码

一、问题

客户端发送以下信息:

Accept-Encoding : gzip, deflate, br

表示支持采用 gzip、deflate 或 br 压缩过的资源

而python3中的 requests只有response.text 和 response.content

  1. response.content
    字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。类型:bytes
  2. reponse.text
    字符串方式的响应体,会自动根据响应头部的字符编码进行解码。类型:str

也就是说requests默认不支持解码br

二、方法

  1. 去除编码类型br
Accept-Encoding = "gzip, deflate"
  1. 使用 brotli 进行页面解析
import brotli

...

if response.headers.get('Content-Encoding') == 'br':
	data = brotli.decompress(response.content)
	return data.decode('utf-8')
else:
	return response.text

...

三、参考文献

[1] willison. python3 requests 爬虫请求头解决gzip, deflate, br中文乱码问题[EB/OL]. 2020-09-09[2023-07-21]. https://www.cnblogs.com/willison/p/13830967.html.
[2] Leo_wl. brotli压缩[EB/OL]. [2023-07-21]. https://www.cnblogs.com/Leo_wl/p/9170390.html.
posted @ 2023-07-21 11:02  Hnyyq  阅读(34)  评论(0)    收藏  举报  来源