python requests cookies example

Python Requests Cookies Example

Python Requests is a popular library used for making HTTP requests in Python. It is widely used because of its simplicity and flexibility. One of the important features of requests is its ability to handle cookies. Cookies are small pieces of data that are stored on the client-side and are used to maintain the state of a user's interaction with a web application.

How to Use Cookies in Python Requests

The requests library provides a cookies attribute that can be used to set and retrieve cookies. Here is an example of how to use cookies in Python Requests:


import requests

# Create a session object
session = requests.Session()

# Set cookies
session.cookies.set('cookie_name', 'cookie_value')

# Send a GET request
response = session.get('https://www.example.com')

# Get cookies
cookies = session.cookies.get_dict()

# Print cookies
print(cookies)

In the above example, we first create a Session object. Then, we set a cookie using the cookies.set() method. Next, we send a GET request to the website and retrieve the cookies using the cookies.get_dict() method. Finally, we print the cookies.

Another Example of Using Cookies in Python Requests

Another way to use cookies in Python Requests is by passing a dictionary of cookies to the get() or post() method. Here is an example:


import requests

# Define cookies as a dictionary
cookies = {
    'cookie_name': 'cookie_value'
}

# Send a GET request with cookies
response = requests.get('https://www.example.com', cookies=cookies)

# Print response content
print(response.content)

In the above example, we define the cookies as a dictionary and pass them to the get() method. The cookies are automatically added to the request headers. Finally, we print the response content.

Conclusion

In this blog post, we have discussed how to use cookies in Python Requests. We have seen two examples of how to set and retrieve cookies. The first example uses the cookies attribute of the Session object, while the second example passes a dictionary of cookies to the get() method. Both methods are simple and easy to use.