当前位置: 移动技术网 > IT编程>脚本编程>Python > 对python requests的content和text方法的区别详解

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

2018年11月09日  | 移动技术网IT编程  | 我要评论

龙猫国语版高清,石桥铺电大月嫂培训,ipv6概念

问题:

一直在想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方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网