python requests的content和text方法的區(qū)別(轉(zhuǎn))(2019-08-08)

原文地址:?http://blog.csdn.net/xie_0723/article/details/51361006

一直在想requests的content和text屬性的區(qū)別,從print 結(jié)果來看是沒有任何區(qū)別的

看下源碼:

@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."""


結(jié)論是:

resp.text返回的是Unicode型的數(shù)據(jù)。

resp.content返回的是bytes型也就是二進制的數(shù)據(jù)。


也就是說,如果你想取文本,可以通過r.text。

如果想取圖片,文件,則可以通過r.content。

(resp.json()返回的是json格式數(shù)據(jù))

舉個栗子


# 例如下載并保存一張圖片

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)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容