Requests库里的text和content属性的区别

官方的文档说明:

>>>>>>>>>>>>>>>>>>>>>>>>>>>  text   <<<<<<<<<<<<<<<<<<<<<<<<<<<
 @property
    def text(self):
        """Content of the response, in unicode."""
                ·········


>>>>>>>>>>>>>>>>>>>>>>>>>>>  content  <<<<<<<<<<<<<<<<<<<<<<<<<<<
@property
    def content(self):
        """Content of the response, in bytes."""
                ·········

  • response.text返回的是Unicode型的数据。
  • response.content返回的是bytes型,也就是二进制的数据。
  • 如果取文本,可以通过r.text。
  • 如果取图片和文件,则可以通过r.content。

例如:

# 下载保存一张图片

# -*- coding:utf-8 -*-
import requests

image_url = 'http://img.infinitynewtab.com/wallpaper/881.jpg'
r = requests.get(image_url)
content = r.content
with open('image.jpg', 'wb') as f:
    f.write(content)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容