溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

對python requests的content和text方法的區(qū)別詳解

發(fā)布時間:2020-08-24 12:18:05 來源:腳本之家 閱讀:131 作者:Op小劍 欄目:開發(fā)技術

問題:

一直在想requests的content和text屬性的區(qū)別,從print 結果來看是沒有任何區(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."""

結論是:

resp.text返回的是Unicode型的數據。

resp.content返回的是bytes型也就是二進制的數據。

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

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

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

舉個栗子

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

import requests

jpg_url = 'https://cache.yisu.com/upload/information/20200622/113/44602.jpg'

content = requests.get(jpg_url).content

with open('demo.jpg', 'wb') as fp:
  fp.write(content)

以上這篇對python requests的content和text方法的區(qū)別詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI