Search code examples
pythoncookieschromiumselenium-webdriver-python

Import browser cookies in JSON format using python


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.


Solution

  • 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.