Selected Reading

Python response.content Attribute



Response.content attribute of the Python Requests module returns the raw bytes of the response content. This attribute is useful for handling binary data such as images, files or any data not suitable for text decoding.

Unlike response.text which decodes the content to a string using a specified encoding where response.content provides the data exactly as received from the server without any decoding.

This attribute is essential when we need to save or process binary files, ensuring the integrity of the original data.

Syntax

Following is the syntax and parameters of Response.content attribute of the Python Requests module −

response.text

Parameter

This attribute does not accept any parameters.

Return value

This method returns the raw response content as a sequence of bytes.

Example 1

Following is the basic example of Response.content attribute of the Python Requests module which makes a GET request and prints the raw bytes of the response content −

import requests

url = 'https://httpbin.org/get'
response = requests.get(url)

print(response.content)

Output

b'{\n  "args": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate, br, zstd", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.31.0", \n    "X-Amzn-Trace-Id": "Root=1-667d3231-6e0c8ed3545ee41631d2e316"\n  }, \n  "origin": "122.171.64.175", \n  "url": "https://httpbin.org/get"\n}\n'

Example 2

Handling binary data in Python often involves working with files such as images, videos, audio files or any other non-text data. The requests module's response.content attribute is useful for accessing and saving such binary data −

import requests

# Define the URL of the large binary file to be downloaded
url = 'https://www.google.com'

# Send a GET request to the URL with stream=True
response = requests.get(url, stream=True)

# Check if the request was successful
if response.status_code == 200:
    # Open a local file in binary write mode
    with open('large_file.zip', 'wb') as file:
        # Iterate over the response in chunks
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                file.write(chunk)
    print('Large file downloaded successfully.')
else:
    print(f'Failed to download large file: {response.status_code}')

Output

Large file downloaded successfully.
python_modules.htm
Advertisements