Request库使用response.text返回乱码问题

我们日常使用Request库获取response.text,这种调用方式返回的text通常会有乱码显示:

import requests

res = requests.get("https://www.baidu.com")
print(res.text)

#...name=tj_briicon class="bri" style="display: block;">更多产品</a> </div> </di...

 

如上:出现了乱码

解决方案:一

import requests

res = requests.get("https://www.baidu.com")
print(res.content.decode('utf-8'))

#...name=tj_briicon class="bri" style="display: block;">更多产品</a> </div> ...

  

如上:使用这种方法调用显示了正确的中文

  使用res.content时,返回的数据格式其实是二进制格式,然后通过decode()转换为utf-8,这样就解决了通过response.text直接返回显示乱码的问题

 

解决方案:二

import requests

res = requests.get("https://www.baidu.com")
res.encoding = 'utf-8'
print(res.text)
#...name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </d...

Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 response.encoding 属性来改变它

posted @ 2019-01-29 17:20  小心走火  阅读(8046)  评论(0编辑  收藏  举报