Python: How to get and set Cookies when using Requests

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# Table of Contents

  1. Python: How to get and set Cookies when using Requests
  2. Accessing the path and the domain when using Cookies with requests
  3. Sending cookies with a request
  4. Accessing the cookies attribute directly on the Response object
  5. Saving the requests cookies in a file and restoring them

# Python: How to get and set Cookies when using Requests

Use the Session class to set and get cookies when using the requests module in Python.

The class creates a Session object that stores the cookies and all requests that are made handle cookies automatically.

main.py
import requests session = requests.Session() print(session.cookies.get_dict()) # {} response = session.get('http://google.com') # {'AEC': 'Ad49MVGzf2rt5u6ObCPLjVzjrRqRMuYhCFG3iH7Ui8-banKZJ3dpZ_4wCA'} print(session.cookies.get_dict())

using cookies in python requests

The code for this article is available on GitHub

Make sure you have the requests module installed to be able to run the code sample.

shell
pip install requests # or with pip3 pip3 install requests

The Session object enables you to persist cookies across requests.

The object persists cookies across all requests that were made using the Session instance.

The Session object has all of the methods of the main requests API.

The get_dict() method returns a Python dictionary of the name-value pairs of cookies.

You can also use Sessions as context managers.

main.py
import requests with requests.Session() as session: print(session.cookies.get_dict()) # {} response = session.get('http://google.com') # {'AEC': 'Ad49MVGzf2rt5u6ObCPLjVzjrRqRMuYhCFG3iH7Ui8-banKZJ3dpZ_4wCA'} print(session.cookies.get_dict())
The code for this article is available on GitHub

Make sure the code that accesses the Session object is inside the indented block.

# Accessing the path and the domain when using Cookies with requests

It is very likely, that you will also have to access the domain and the path to which the request was made when accessing the cookies.

You can use a list comprehension to construct a list of dictionaries that contain the path and domain.

main.py
import requests session = requests.Session() print(session.cookies.get_dict()) # {} print('-' * 50) response = session.get('http://google.com') # {'AEC': 'Ad49MVGzf2rt5u6ObCPLjVzjrRqRMuYhCFG3iH7Ui8-banKZJ3dpZ_4wCA'} print(session.cookies.get_dict()) print('-' * 50) result = [ {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path} for c in session.cookies ] # [{'name': 'AEC', 'value': 'Ad49MVGjcnQKK55wgCKVdZpw4PDgEgicIVB278lObJdf4eXaYChtDZcGLA', 'domain': '.google.com', 'path': '/'}] print(result)

get path and domain while using cookies in requests

The code for this article is available on GitHub

We used a list comprehension to iterate over the RequestCookieJar object (session.cookies) and returned a dictionary on each iteration.

The dictionary contains the name and value of the cookie, the path and the domain.

# Sending cookies with a request

If you want to send cookies with a request, set the cookies keyword argument.

main.py
import requests session = requests.Session() response = session.get( 'https://httpbin.org/cookies', cookies={'my-cookie': 'my-value'} ) # { # "cookies": { # "my-cookie": "my-value" # } # } print(response.text)

send cookies with request

The code for this article is available on GitHub

We set the cookies keyword argument to a dictionary of key-value pairs.

# Accessing the cookies attribute directly on the Response object

In more recent versions of the requests module, you can also access the cookies attribute directly on the Response object.

main.py
import requests response = requests.get('http://google.com', timeout=30) # {'AEC': 'Ad49MVE4KO7sQX_pRIifPtDvL666jJcj34BmOFeETG9YU_1mu1SINQN-Q_A'} print(response.cookies.get_dict()) result = [ {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path} for c in response.cookies ] # [{'name': 'AEC', 'value': 'Ad49MVGjcnQKK55wgCKVdZpw4PDgEgicIVB278lObJdf4eXaYChtDZcGLA', 'domain': '.google.com', 'path': '/'}] print(result)

accessing cookies attribute directly on response object

The code for this article is available on GitHub

Notice that we didn't instantiate the Session class.

We simply accessed the cookies attribute on the Response object and called the get_dict() method on the RequestCookieJar object.

However, the management of cookies is automated when you use a Session object.

This means that you won't have to send the cookies explicitly:

main.py
import requests session = requests.Session() response = session.get( 'https://httpbin.org/cookies', cookies={'my-cookie': 'my-value'} ) # { # "cookies": { # "my-cookie": "my-value" # } # } print(response.text)

Because it will be done for you automatically.

# Saving the requests cookies in a file and restoring them

You can also save the requests cookies in a file.

main.py
import json import requests response = requests.get('http://google.com', timeout=30) with open('cookies.txt', 'w', encoding='utf-8') as f: json.dump( requests.utils.dict_from_cookiejar(response.cookies), f )
The code for this article is available on GitHub

The cookies.txt file stores the following JSON string.

main.py
{"AEC": "Ad49MVEu4N64Tk1gEROw417s9FgcqdqeIeVZ8eL9m-HQldzOrLAF2HvxHQ"}

Notice that we used the requests.utils.dict_from_cookiejar method to create a dictionary from the RequestCookieJar object.

We then passed the dictionary and the file object to the json.dump method.

The json.dump() method serializes the supplied object as a JSON formatted stream and writes it to a file.

You can then read and restore the cookies from the file.

main.py
import json import requests session = requests.session() with open('cookies.txt', 'r', encoding='utf-8') as f: cookies = requests.utils.cookiejar_from_dict(json.load(f)) session.cookies.update(cookies) # {'AEC': 'Ad49MVEu4N64Tk1gEROw417s9FgcqdqeIeVZ8eL9m-HQldzOrLAF2HvxHQ'} print(session.cookies.get_dict())
The code for this article is available on GitHub

We created a brand new Session object but you can use an existing Session.

  1. We used the json.load() method to convert the contents of the file to a native Python dictionary.
  2. We used the requests.utils.cookiejar_from_dict method to create a RequestCookieJar object from the dictionary.
  3. The last step is to update the cookies of the Session object with the newly read cookies.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.