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

yipeiwu_com6年前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实现1-9数组形成的结果为100的所有运算式的示例

问题: 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34–5 + 67–8 + 9 =...

Python 确定多项式拟合/回归的阶数实例

Python 确定多项式拟合/回归的阶数实例

通过 1至10 阶来拟合对比 均方误差及R评分,可以确定最优的“最大阶数”。 import numpy as np import matplotlib.pyplot as plt f...

浅谈python中字典append 到list 后值的改变问题

看一个例子 d={'test':1} d_test=d d_test['test']=2 print d 如果你在命令行实践的话,会发现你改动的是d_test ,但是d 也跟着改变...

python将一个英文语句以单词为单位逆序排放的方法

例如“I am a boy”,逆序排放后为“boy a am I”所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符。 list_number = list(inpu...

Python使用稀疏矩阵节省内存实例

推荐系统中经常需要处理类似user_id, item_id, rating这样的数据,其实就是数学里面的稀疏矩阵,scipy中提供了sparse模块来解决这个问题,但scipy.spar...