Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requests.Session() load cookies from CookieJar

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.

like image 704
Ranama Avatar asked Dec 25 '22 21:12

Ranama


1 Answers

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).
like image 130
Mitch McMabers Avatar answered Dec 27 '22 12:12

Mitch McMabers