Python response.text Attribute
Response.text attribute of the Python Requests module provides the content of a response decoded as a string using the detected encoding. When we make an HTTP request using 'requests' and the 'response' object containing the server's response to our request.
The text attribute of this object automatically decodes the content from bytes to a string based on the charset specified in the HTTP headers for example Content-Type header. If the charset is not specified then it defaults to ISO-8859-1.
This attribute is useful for reading the response content in a human-readable format such as HTML, JSON or plain text.
Syntax
Following is the syntax and parameters of Response.text attribute of the Python Requests module −
response.text
Parameter
This attribute does not accept any parameters.
Return value
This method returns the content of the response as a string.
Example 1
Following is the basic example of the Response.text attribute of the Python Requests module which makes a GET request to the URL and prints the response content as a string −
import requests url = 'https://httpbin.org/get' response = requests.get(url) print(response.text)
Output
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.31.0",
"X-Amzn-Trace-Id": "Root=1-667bf720-14dc9bff720bb0863f76e4d6"
},
"origin": "122.181.50.101",
"url": "https://httpbin.org/get"
}
Example 2
When working with plain text content retrieved from a URL using requests in Python we can directly access and process the text using the response.text attribute. Heres an example that demonstrates how to handle plain text content −
import requests
# Define the URL of the plain text file
url = 'https://www.google.com'
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Access the plain text content
text_content = response.text
# Example: Print the first 100 characters of the text content
print('First 100 characters of the text:')
print(text_content[:100])
# Example: Count the number of lines in the text content
lines = text_content.splitlines()
print('Number of lines in the text:', len(lines))
# Example: Search for a specific substring in the text content
search_term = 'google'
if search_term in text_content:
print(f'Found "{search_term}" in the text content.')
else:
print(f'"{search_term}" not found in the text content.')
else:
print(f'Failed to download text file: {response.status_code}')
Output
First 100 characters of the text: <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta cont Number of lines in the text: 18 Found "google" in the text content.
python_modules.htm