Python Requests Set Cookie
Python Requests is a widely used library for making HTTP requests in Python. In this blog post, we will discuss how to set cookies in a request using Python Requests.
What are Cookies?
Cookies are small pieces of data that are stored on a user's computer by a web server. Cookies are used to remember user preferences, login information, and other details. Cookies can be set by the server and read by the client or vice versa.
Setting Cookies using Python Requests
In Python Requests, cookies can be set using the cookies
parameter. The cookies
parameter takes a dictionary of name-value pairs representing the cookies to be set.
import requests
# Create a session object
s = requests.Session()
# Set cookies
cookies = {'name': 'value'}
# Make a GET request with cookies
response = s.get('https://example.com', cookies=cookies)
# Print response text
print(response.text)
In the above example, we created a session object and set the cookies using a dictionary. We then made a GET request to 'https://example.com' with the cookies. The response text is printed using the print()
function.
Multiple Cookies
If you want to set multiple cookies, you can do so by adding additional key-value pairs to the dictionary.
import requests
# Create a session object
s = requests.Session()
# Set multiple cookies
cookies = {'name1': 'value1', 'name2': 'value2'}
# Make a GET request with cookies
response = s.get('https://example.com', cookies=cookies)
# Print response text
print(response.text)
Cookie Expiration
You can set the expiration time for a cookie by adding the expires
parameter to the dictionary. The expires
parameter takes a datetime object representing the expiration time.
import requests
import datetime
# Create a session object
s = requests.Session()
# Set cookie with expiration time
expiration = datetime.datetime.now() + datetime.timedelta(days=1)
cookies = {'name': 'value', 'expires': expiration}
# Make a GET request with cookies
response = s.get('https://example.com', cookies=cookies)
# Print response text
print(response.text)
In the above example, we set the expiration time for the cookie to be one day from the current time using the datetime.timedelta()
function.
Conclusion
In this blog post, we discussed how to set cookies in a request using Python Requests. We learned that cookies are small pieces of data that are stored on a user's computer by a web server and can be used to remember user preferences, login information, and other details. We also learned that cookies can be set using the cookies
parameter in Python Requests and that multiple cookies can be set by adding additional key-value pairs to the dictionary.