requests.Session() load cookies from CookieJar

Ranama picture Ranama · Mar 22, 2015 · Viewed 14.4k times · Source

How can I load a CookieJar to a new requests.Session object?

cj = cookielib.MozillaCookieJar("mycookies.txt")
s = requests.Session()

This is what I create, now the session will store cookies, but I want it to have my cookies from the file
(The session should load the cookieJar). How can this be achieved?
I searched the documentation but I can only find code examples and they are never loading a cookieJar, just saving cookies during one session.

Answer

Mitch McMabers picture Mitch McMabers · May 31, 2020

Python 3.x code, fully working and well-implemented example. The code is self-explanatory.

This code properly handles "session cookies", preserving them between runs. By default, those are not saved to disk, which means that most websites would require you to constantly login between runs. But with the technique below, all session cookies are kept too!

This is the code you are looking for.

import os
import pathlib
import requests
from http.cookiejar import MozillaCookieJar


cookiesFile = str(pathlib.Path(__file__).parent.absolute() / "cookies.txt")  # Places "cookies.txt" next to the script file.
cj = MozillaCookieJar(cookiesFile)
if os.path.exists(cookiesFile):  # Only attempt to load if the cookie file exists.
    cj.load(ignore_discard=True, ignore_expires=True)  # Loads session cookies too (expirydate=0).

s = requests.Session()
s.headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    "Accept-Language": "en-US,en"
}
s.cookies = cj  # Tell Requests session to use the cookiejar.

# DO STUFF HERE WHICH REQUIRES THE PERSISTENT COOKIES...
s.get("https://www.somewebsite.com/")

cj.save(ignore_discard=True, ignore_expires=True)  # Saves session cookies too (expirydate=0).