对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设计】。

相关文章

python标准日志模块logging的使用方法

python标准日志模块logging的使用方法

最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下。python的标准库里的日志系统从Python2.3开始支持。只要import logging这个模块即可使用。...

介绍Python中的一些高级编程技巧

 正文: 本文展示一些高级的Python设计结构和它们的使用方法。在日常工作中,你可以根据需要选择合适的数据结构,例如对快速查找性的要求、对数据一致性的要求或是对索引的要求等,...

python实现简易学生信息管理系统

python实现简易学生信息管理系统

本文实例为大家分享了python实现学生信息管理系统的具体代码,供大家参考,具体内容如下 简易学生信息管理系统主要功能有 1 录入学生信息 2 查找学生信息 3 删除学生信息 4 修改学...

Pytorch之parameters的使用

1.预构建网络 class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1...

Python中你应该知道的一些内置函数

Python中你应该知道的一些内置函数

前言 python内置了一些非常巧妙而且强大的内置函数,对初学者来说,一般不怎么用到,我也是用了一段时间python之后才发现,哇还有这么好的函数,这个函数都是经典的而且经过严格测试的,...