python requests get cookies

Python Requests Get Cookies

When using Python Requests to make HTTP requests, cookies are often used to keep track of user sessions, authentication, and other data. The requests library provides a convenient way to get and manage cookies in your Python programs.

Getting Cookies Using Requests

To get cookies from a response in Python Requests, you can use the cookies attribute of the response object. This attribute returns a dictionary-like object that contains the cookies set by the server.


import requests

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

cookies = response.cookies
print(cookies)
    

In the above example, we are making a GET request to a URL and storing the response object in the variable response. We then use the cookies attribute to get the cookies that were set by the server. Finally, we print out the cookies.

Using Cookies in Subsequent Requests

Once you have obtained cookies from a response, you can use them in subsequent requests by passing them in the cookies parameter of the request method.


import requests

url = 'https://www.example.com'
cookies = {'session_id': '1234'}

response = requests.get(url, cookies=cookies)
print(response.content)
    

In the above example, we are passing in a dictionary of cookies to the get method using the cookies parameter. This will send the cookies with the request and allow us to access protected resources that require authentication.

Conclusion

Python Requests provides a simple way to get and manage cookies in your Python programs. By using the cookies attribute of the response object, you can easily access cookies set by the server. You can also pass cookies in subsequent requests using the cookies parameter of the request method.