对python requests的content和text方法的区别详解
问题:
一直在想requests的content和text属性的区别,从print结果来看是没有任何区别的
看下源码:
@property deftext(self): """Contentoftheresponse,inunicode. IfResponse.encodingisNone,encodingwillbeguessedusing ``chardet``. TheencodingoftheresponsecontentisdeterminedbasedsolelyonHTTP headers,followingRFC2616totheletter.Ifyoucantakeadvantageof non-HTTPknowledgetomakeabetterguessattheencoding,youshould set``r.encoding``appropriatelybeforeaccessingthisproperty. """ #content的完整代码就不贴了。 @property defcontent(self): """Contentoftheresponse,inbytes."""
结论是:
resp.text返回的是Unicode型的数据。
resp.content返回的是bytes型也就是二进制的数据。
也就是说,如果你想取文本,可以通过r.text。
如果想取图片,文件,则可以通过r.content。
(resp.json()返回的是json格式数据)
举个栗子
#例如下载并保存一张图片
importrequests
jpg_url='http://img2.niutuku.com/1312/0804/0804-niutuku.com-27840.jpg'
content=requests.get(jpg_url).content
withopen('demo.jpg','wb')asfp:
fp.write(content)
以上这篇对pythonrequests的content和text方法的区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下