A detailed explanation of the differences between content and text methods of python requests

  • 2020-12-10 00:45:45
  • OfStack

Question:

1 I have been thinking about the difference between content and text attributes of requests, and there is no difference from print results

Look at the source code:


@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 The complete code is not posted. 
  @property
  def content(self):
    """Content of the response, in bytes."""

The conclusion is:

resp.text returns data for the Unicode type.

resp.content returns the bytes, or base 2 data.

In other words, if you want to get the text, you can go to r.text.

If you want to get the image, the file, you can go to r.content.

(resp. json() returns data in json format)

Take a chestnut


#  For example, download and save 1 image 

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)

Related articles: