Python requests中content与text属性的核心区别解析
本文详解Python requests库中content与text属性的区别。text返回Unicode字符串,自动处理编码;content返回bytes二进制数据。获取文本用text,下载图片文件用content。
问题:
许多开发者在初次使用时,常疑惑requests库中content和text属性的具体差异。仅从print输出的结果来看,两者似乎没有明显区别。
为厘清这一疑惑,我们需要深入查看其源码实现逻辑:
@property
def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
#content的完整代码就不贴了。
@property
def content(self):
"""Content of the response, in bytes."""
通过源码分析,可以得出以下明确结论:
resp.text返回的是经过解码的Unicode型字符串数据。
resp.content返回的是原始的bytes型二进制数据。
因此,若你的目标是获取网页文本内容,应当使用r.text。
若你的目标是获取图片、文件等二进制资源,则应当使用r.content。
(注:resp.json()用于返回解析后的json格式数据,与上述两者不同)
举个栗子
# 例如下载并保存一张图片
import requests
jpg_url = 'http://img2.niutuku.com/1312/0804/0804-niutuku.com-27840.jpg'
content = requests.get(jpg_url).content
with open('demo.jpg', 'wb') as fp:
fp.write(content)
以上这篇对python requests的content和text方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









