Last updated: Apr 11, 2024
Reading time · 4 min
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.
The code for this article is available on GitHubCopied!import requests session = requests.Session() print(session.cookies.get_dict()) # <> response = session.get('http://google.com') # print(session.cookies.get_dict())
Make sure you have the requests module installed to be able to run the code sample.
Copied!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.
The code for this article is available on GitHubCopied!import requests with requests.Session() as session: print(session.cookies.get_dict()) # <> response = session.get('http://google.com') # print(session.cookies.get_dict())
Make sure the code that accesses the Session object is inside the indented block.
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.
The code for this article is available on GitHubCopied!import requests session = requests.Session() print(session.cookies.get_dict()) # <> print('-' * 50) response = session.get('http://google.com') # 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 ] # [] print(result)
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.
If you want to send cookies with a request, set the cookies keyword argument.
The code for this article is available on GitHubCopied!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)
We set the cookies keyword argument to a dictionary of key-value pairs.
In more recent versions of the requests module, you can also access the cookies attribute directly on the Response object.
The code for this article is available on GitHubCopied!import requests response = requests.get('http://google.com', timeout=30) # print(response.cookies.get_dict()) result = [ 'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path> for c in response.cookies ] # [] print(result)
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:
Copied!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.
You can also save the requests cookies in a file.
The code for this article is available on GitHubCopied!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 cookies.txt file stores the following JSON string.
Copied!"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.
The code for this article is available on GitHubCopied!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) # print(session.cookies.get_dict())
We created a brand new Session object but you can use an existing Session .
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.