Last updated: Apr 11, 2024
Reading time·4 min
Response
objectrequests
cookies in a file and restoring themUse 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.
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())
Make sure you have the requests module installed to be able to run the code sample.
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.
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())
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.
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)
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.
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.
Response
objectIn more recent versions of the requests
module, you can also access the
cookies
attribute directly on the Response
object.
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)
Notice that we didn't instantiate the Session
class.
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:
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.
requests
cookies in a file and restoring themYou can also save the requests
cookies in a file.
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.
{"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.
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())
We created a brand new Session
object but you can use an existing Session
.
json.load()
method to convert the contents of the file to a
native Python dictionary.requests.utils.cookiejar_from_dict
method to create a
RequestCookieJar
object from the dictionary.Session
object with the newly
read cookies.You can learn more about the related topics by checking out the following tutorials: