Python requests中content与text属性的核心区别解析

陆遥
陆遥
发布时间:2026-10-13| 5人浏览过
原创

本文详解Python requests库中content与text属性的区别。text返回Unicode字符串,自动处理编码;content返回bytes二进制数据。获取文本用text,下载图片文件用content。

问题:

许多开发者在初次使用时,常疑惑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方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。