平时我们使用 requests 时, 通过两种方法拿到响应的内容:
import requests
response = requests.get('https://example.com')
a = response.content # type: bytes
b = response.text # type: str
其中 response.text
是我们常用的.
requests 的作者在注释中这样写道:
意思是说, response.text
是以 response.content
(字节码) 和 encoding (编码) 为根据, 将字节码转换成 str 返还给我们的.
换句话说就是, response.text
自动帮我们把从服务器获得的字节流转换成 str 返还给我们, 为我们减去了各种网页编码带来的 “乱码” 的问题.
那么为什么 response.text
仍然有时候会出现乱码的问题呢?
这就是本文要解释的问题, 接下来我会一个例子说明.
这是一个有 “问题” 的网页: http://www.most.gov.cn/ztzl/gjkxjsjldh/jldh2002/zrj/zrjml.htm
在浏览器中打开它, 显示的是正常的:
而通过 response.text
查看就会出现乱码.
首先, requests 在计算 response.text
的时候, 会先看响应的 http header 中是否提供了 encoding 信息. 我们通过 response.encoding
可以拿到这个值. 可以看到, 确实是有的, 是 “ISO-8859-1”.
按理来说, 网页已经告诉我们, 它用的是 “ISO-8859-1” 编码, 于是 requests 就信以为真, 拿 “ISO-8859-1” 来解析字节流, 转换为字符串, 于是我们就看到 response.text 的乱码了 - 问题就出在, 网页告诉了爬虫一个错误的编码信息.
那么我们提出新的思路, 如果我们不使用 http header 提供的 encoding, 而采用其他方法获知 encoding 有没有可能呢?
requests 确实有此方法, 不过是在 http header 提供的 encoding 为 None 时才会用. 它通过 chardet (一个 Python 第三方模块, 用来预测文件编码) 来检测网页最可能用的是哪种编码. 注意这里是 “可能用的”, 因为 chardet 的原理就是用各种编码来试, 直到找出一个看起来不像是乱码的情况.
我们通过 response.apparent_encoding
可以拿到这个值. 可以看到, chardet 预测的编码是 “GB2312”.
这里给一个小提示, GB2312 的字符集实在是太小了, 我们最好使用它的超集 GBK 来替代, 以避免某些生僻字解码不出来:
# result = response.content.decode(encoding='GB2312') # abandoned
result = response.content.decode(encoding='GBK') # suggest
另外还要注意的是, 在解码的过程中, 可能会遇到字符集以外的未知标识导致解码中断并报错, 添加一个 errors 参数可以避免此问题:
result = response.content.decode(encoding='GBK', errors="ignore")
# result = response.content.decode(encoding='GBK', errors="replace")
errors='ignore'
的效果如下:
erros='replace'
的效果如下:
总结一下, response.text
造成乱码的原因不外乎两种: 要么是网页提供了错误的编码 (比如上例中的网页, 明明是中文网页却提供了一个纯西文字符集 “ISO-8859-1”), 要么是 chardet 预测的编码不当 (比如取了某个编码的子集, 导致大量生僻字显示为乱码).
(另外想说一句, 对于 pdf, jpg 等二进制文件 url, response.encoding
, response.apparent_encoding
给出的结果都是 None.)
了解了这些以后, 我们就有办法自己动手, 解决乱码了.
import requests
def get_text(resp):
# 优先使用 chardet 预测的 encoding, 其次使用 http header 提供的 encoding
source_encoding = resp.apparent_encoding or resp.encoding
if source_encoding is None:
# 说明是二进制文件, 比如 pdf, jpg 之类的
raise Exception
elif source_encoding == 'GB2312':
source_encoding = 'GBK'
return resp.content.decode(source_encoding, errors="ignore")
# 测试 "问题" 网页
url = 'http://www.most.gov.cn/ztzl/gjkxjsjldh/jldh2002/zrj/zrjml.htm'
response = requests.get(url)
text = get_text(response)
# | text = response.text # 不用这个了
# 保存为文件
with open('result.html', 'w', encoding='utf-8') as f:
f.write(text)