python中的content方法_对python requests的content和text方法的区别详解

编程知识 更新时间:2023-04-05 05:18:59

问题:

一直在想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/1312/0804/0804-niutuku-27840.jpg'

content = requests.get(jpg_url).content

with open('demo.jpg', 'wb') as fp:

fp.write(content)

以上这篇对python requests的content和text方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多推荐

python中的content方法_对python requests的content和text方法的区别详解

本文发布于:2023-04-05 05:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/e3e7fd229df42b5b9a5146824c0ac71e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   详解   区别   python   content

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 44973文章数
  • 14阅读数
  • 0评论数