pythoncookiespython-requestspicklecookiejar

How to use google chrome cookies stored in text file with python get request?


Sending google chrome cookies directly to python get requests works perfectly fine using the approach below,

import requests
import browsercookie
data = requests.get(url, cookies=browsercookie.chrome())

But for a very specific use-case, I need to store google chrome cookies in a file and use them (in future) while making a python get request to call as stated above,

I am storing google chrome cookies in a text file as shown below,

import browsercookie
import pickle
pickle.dump(browsercookie.chrome()._cookies, open("cookies.pkl","wb"))

But I think there is some cookie format issue in the loaded cookies from "cookies.pkl" -- AND THIS DOES NOT WORK...

import requests
import browsercookie
import pickle
cj = pickle.load(open("imdb_cookies.pkl", "rb"))
data = requests.get(url, cookies=cj)

Error --

Error: expected string or bytes-like object

I think the cookie dictionary loaded from "cookies.pkl" needs to be converted to ""...

I tried researching a lot but could not find a solution.

If there is any other way where cookies can be stored to files and used in the future, please do let me know...


Solution

  • I followed a different approach and it worked. Instead of using pickle. I used a google chrome extension called cookie.txt. Used that extension to store cookies in cookie.txt. Then used the cookie.txt in the following way with python requests,

    import http.cookiejar as cookielib
    cj = cookielib.MozillaCookieJar('cookies.txt')
    cj.load()
    data = requests.get(url, cookies=cj)