微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

今天小编就为大家分享一篇对python requests的content和text方法的区别详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

问题:

一直在想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方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐