python requests的content和text方法的區別(轉)

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

  • 問題:
一直在想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。app

若是想取圖片,文件,則能夠經過r.content。this

(resp.json()返回的是json格式數據)url

舉個栗子spa

# 例以下載並保存一張圖片

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)
相關文章
相關標籤/搜索