1

I've been trying to get selenium to import JSON cookies to a website (from a file: "cookie.json") but I don't really know how to go about doing that. Most I've tried so far is "driver.add_cookie(cookie1)" with the variable leading to the cookie file path. The cookie looks like this and was exported from a site.

[
    {
        "domain": ".domain.com",
        "expirationDate": 1636199697,
        "hostOnly": false,
        "httpOnly": false,
        "name": "-------------",
        "path": "/",
        "sameSite": null,
        "secure": false,
        "session": false,
        "storeId": null,
        "value": "1.1.1016649666.1628423698"
    },
    {
        "domain": ".domain.com",
        "expirationDate": 1644600003.576958,
        "hostOnly": false,
        "httpOnly": true,
        "name": "grauth",
        "path": "/",
        "sameSite": "no_restriction",
        "secure": true,
        "session": false,
        "storeId": null,
        "value": "AABJpmDto2N7IweClTj1oGh67yhbpAdufysidUIDfPmbOrBc4ASFnGqBoezsGp6I"
    },
    {
....

Someone asked what I've tried

with open('cookies.json', 'wb') as load_cookies:
    cookies = json.load(load_cookies)
cookie = cookies[0]
chrome = webdriver.Chrome(executable_path=PATH, options=options)
chrome.get("https://example.com")
chrome.add_cookie(cookie)

The above code snippet is something I found online.

& this

browser.get(url)
def add_cookies():
    with open('cookies.json','rb') as f:
        cookies = json.load(f)
        for item in cookies:
            browser.add_cookie(item)

The above is something that I wrote.

I should add that the cookies come from chrome cookie exporting programs like Editthiscookie. Hopefully, this will help. I've gone through a bunch of random forums and it seems to work fine for other people. I'm 100% doing something wrong here.

Anthony
  • 33
  • 1
  • 9
  • Please add Python code snippet which you tried. SO expects you to [try to solve the problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Show your effort. – kkgarg Aug 15 '21 at 20:48

1 Answers1

1

Found this on a random Chinese forum and it worked.

for cookie in cookieList:
    driver.add_cookie({k: cookie[k] for k in {'name','value'}})

The cookies do import, but it brings up an ERR_TOO_MANY_REDIRECTS error.

Anthony
  • 33
  • 1
  • 9
  • It is giving this error :- driver.add_cookie({k: cookie[k] for k in {'name','value'}}) ~~~~~~^^^ TypeError: string indices must be integers, not 'str' – nothing Nov 20 '22 at 06:29
  • this is how I declare cookieList: cookieList = json.loads(verifyThis) and verifyThis is a JSON cookie.. Maybe that will help? @nothing sorry for a late response, just in case someone else has the same problem i commented. – Anthony Jan 22 '23 at 19:25
  • Worked perfectly, thanks. – siditious Jul 08 '23 at 05:31