Python-requests内容编码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kwoky/article/details/87918618

问题:

用requests请求页面,用print(req.encoding)查看网页编码,有时候会显示:ISO-8859-1

原因:

requests会从服务器返回的响应头的 Content-Type 去获取字符集编码,如果content-type有charset字段那么requests才能正确识别编码,否则就使用默认的 ISO-8859-1. 一般那些不规范的页面往往有这样的问题.

解决办法:

response.encoding = response.apparent_encoding

requests的返回结果对象里有个apparent_encoding函数, apparent_encoding通过调用chardet.detect()来识别文本编码

猜你喜欢

转载自blog.csdn.net/Kwoky/article/details/87918618