HTTP标准中默认的编码格式是ISO-8859-1,当响应头中未指定charset时,requests库就会使用默认编码进行解码。
但一些网站并未遵循此标准,在不提供charset字段的同时未使用默认编码,就会导致requests编码错误。

所以,当编码是默认的ISO-8859-1时,就有检查网页真正编码的必要。
首先使用get_encodings_from_content函数得到相应的真正编码,它会使用正则表达式的方式,从响应内容中探测编码(如HTML head中的meta)。

如果通过上述方法并未成功,还可以通过apparent_encoding方法,通过响应的内容来探测出编码。

下面时代码示例:

1
2
3
4
5
6
7
8
9
if r.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(r.text)
if encodings:
encoding = encodings[0]
else:
encoding = r.apparent_encoding
encode_content = r.content.decode(encoding, 'replace').encode('utf-8', 'replace')
else:
encode_content = r.text