python requests get response body

Python Requests Get Response Body

When you send a GET request to a web server, the server responds with a response object that contains the data you requested. To access this response body in Python, you can use the requests library. Here's how:

Step 1: Import the Requests Library

To use the requests library, you must first import it into your Python script. You can do this using the following code:


import requests

Step 2: Send a GET Request

Now that you have the requests library imported, you can send a GET request to the web server using the requests.get() function. Here's an example:


response = requests.get('https://www.example.com')

This sends a GET request to the URL https://www.example.com and stores the response object in the response variable.

Step 3: Access the Response Body

To access the response body, you can simply use the response.text attribute. Here's an example:


print(response.text)

This will print the response body as a string.

Using highlight.js for Syntax Highlighting

If you want to display your code with syntax highlighting on your website or blog, you can use highlight.js. Here's an example of how to use it:


<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/styles/default.min.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/highlight.min.js"></script>
    <script>hljs.initHighlightingOnLoad();</script>
  </head>
  <body>
    <pre><code class="python">
import requests

response = requests.get('https://www.example.com')
print(response.text)
</code></pre>
  </body>
</html>

This will display the code with syntax highlighting for the Python language.

Summary

In summary, to access the response body in Python using the requests library, you must first import the library, send a GET request to the web server, and then access the response body using the response.text attribute. To display your code with syntax highlighting, you can use highlight.js.