解决Requests库编码问题
HTTP标准中默认的编码格式是ISO-8859-1
,当响应头中未指定charset
时,requests
库就会使用默认编码进行解码。
但一些网站并未遵循此标准,在不提供charset
字段的同时未使用默认编码,就会导致requests
编码错误。
所以,当编码是默认的ISO-8859-1
时,就有检查网页真正编码的必要。
首先使用get_encodings_from_content
函数得到相应的真正编码,它会使用正则表达式的方式,从响应内容中探测编码(如HTML head中的meta)。
如果通过上述方法并未成功,还可以通过apparent_encoding
方法,通过响应的内容来探测出编码。
下面时代码示例:
1 | if r.encoding == 'ISO-8859-1': |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 才才才的Blog!