以请求百度为例,看看response.text和response.content有哪些不同:
-
response.content
import requests
response = requests.get("http://www.baidu.com")
response.content
>>>
可以看出输出的字符串类型为bytes。为了获取正确的字符串需要对response进行解码。
这样就正常了,这里不添加参数时默认使用的是“utf-8"的编码方式。当然也可以指定参数,response.content.decode("gbk")
-
response.text
可以看出text输出下有些问题:乱码。这是因为response.text在解码时会根据HTTP头部对响应的编码做出推测,推测文本的编码。通过response.encoding属性查看它推测出的编码类型。
推测成了”ISO-8859-1“,显然是推测错了。所以我们试试utf-8类型的编码:
这样就没有什么问题了。
总结:
这三种解码的方法应该能解决遇到的所有情况了
1、response.text和response.content的区别
- response.text
类型:str
编码类型:根据HTTP头部对响应的编码做出推测,推测文本的编码
修改编码方式:response.encoding="gbk"
- response.content
类型:bytes
解码类型:没有指定
修改编码方式:response.content.decode("utf-8")
2、requests中解决编解码的方法
- response.content.decode()
- response.content.decode("gbk")
- response.text