Requests Session Example
If you want to make HTTP requests to a website using Python, the Requests library is a great tool to use. It allows you to send HTTP requests and handle responses with ease. One of the features of Requests is the Session object, which can be used to persist parameters across requests.
Creating a Session
To create a Session object, you simply need to import the requests module and call the Session() method:
import requests
session = requests.Session()
Sending Requests
Once you have a Session object, you can use it to send HTTP requests. The Session object has methods for making various types of HTTP requests, such as GET, POST, PUT, DELETE, and more. Here's an example of sending a GET request:
response = session.get('https://www.example.com')
The response object contains the server's response to the request. You can access various properties of the response object, such as the status code, headers, and content:
print(response.status_code)
print(response.headers)
print(response.content)
Handling Cookies
Sessions are particularly useful for handling cookies. When you make a request using a Session object, any cookies returned by the server are stored in the Session object. You can then use those cookies in subsequent requests.
Here's an example of using a Session to log in to a website and then accessing a page that requires authentication:
login_data = {
'username': 'myusername',
'password': 'mypassword'
}
session.post('https://www.example.com/login', data=login_data)
response = session.get('https://www.example.com/protected_page')
print(response.content)
In this example, we first send a POST request to the login page with our login credentials. The server returns a set of cookies, which are stored in the Session object. We can then use the same Session object to send a GET request to a protected page, and the server will recognize our session and allow us to access the page.