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

相关文章

在pycharm中使用git版本管理以及同步github的方法

在pycharm中使用git版本管理以及同步github的方法

注意:首先你电脑必须安装git版本控制器(软件),在官网下载即可。 pycharm中使用git以及github很简单,首先在设置中搜索github: 点击右边的Create API T...

python strip()函数 介绍

描述 Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。 语法 strip()方法语法: str.strip([chars]); 参数 chars -- 移除...

Python使用grequests(gevent+requests)并发发送请求过程解析

前言 requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。...

python脚本设置系统时间的两种方法

本文为大家分享了两种python脚本设置系统时间的方法,供大家参考,具体内容如下 第一种方法,使用Python设置系统时间,即给系统校时 #电脑时间用了一段时间后,系统时间不准了,...

python线程池(threadpool)模块使用笔记详解

最近在做一个视频设备管理的项目,设备包括(摄像机,DVR,NVR等),包括设备信息补全,设备状态推送,设备流地址推送等,如果同时导入的设备数量较多,如果使用单线程进行设备检测,那么由于设...