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

yipeiwu_com5年前Python基础

问题:

一直在想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 = '/zb_users/upload/202003/o4acg1gwtjk.jpg'

content = requests.get(jpg_url).content

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

以上这篇对python requests的content和text方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pandas 条件搜索返回列表的方法

pandas中常用的一件事情就是对特定条件进行搜索,那么这里介绍使用pandas搜索方式,本案例使用的pandas是anaconda中的,可以下载任意的anaconda进行安装都会带有。...

10分钟教你用Python实现微信自动回复功能

10分钟教你用Python实现微信自动回复功能

 01 前言&&效果展示 相信大家都有忙碌的时候,不可能一直守在微信上及时回复消息。但微信又不能像QQ一样设置自动回复。无妨,今天,我们就来用Python实现微信的自动回复功能...

python生成式的send()方法(详解)

随便在网上找了找,感觉都是讲半天讲不清楚,这里写一下。 def generator(): while True: receive=yield 1 print('e...

python生成IP段的方法

python生成IP段的方法

本文实例讲述了python生成IP段的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/local/bin/python #-*- coding: UTF-8 -*- #...

示例详解Python3 or Python2 两者之间的差异

示例详解Python3 or Python2 两者之间的差异

每门编程语言在发布更新之后,主要版本之间都会发生很大的变化。 在本文中,Vinodh Kumar 通过示例解释了 Python 2 和 Python 3 之间的一些重大差异,以帮助说明语...