requests获取内容无法解码
requests 获取内容后出现乱码(如显示为 æµè¯ 或 ����),通常是由两个原因造成的:编码识别错误 或 压缩格式不支持。
- 手动设置编码(大概率)
- 处理 Brotli (br) 压缩(常见坑点,重点关注)
方法 A (推荐):安装 brotli 库,requests 就能自动解压了。
方法 B:告诉服务器“我不支持 br 压缩”,让它返回普通的 gzip 或未压缩内容。
'Accept-Encoding': 'gzip, deflate' - 自动检测编码(最稳妥)
response = requests.get("http://example.com")
detected = chardet.detect(response.content)
print("检测到的编码:", detected) # 例如 {'encoding': 'GB2312', 'confidence': 0.99}