cordmana
cordmana

Reputation: 151

Problem loading cookies with selenium and python

I am trying to access a webpage, save the cookie to a csv file, and then use cookie later all with selenium and python. Currently, I can save cookies perfectly fine, but then when I try to use that cookie later, I get the following error:

selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: missing 'cookie'
  (Session info: chrome=84.0.4147.89)

Here is my code to save the cookie:

from selenium import webdriver
import csv
outputdata = open('cookietest.csv', 'w', newline='')
outputWriter = csv.writer(outputdata)
driver=webdriver.Chrome()
driver.get("https://stackoverflow.com/")
cookies = driver.get_cookies()
print(cookies)
outputWriter.writerow([cookies])

And here is my code to load a webpage with thus cookies:

import csv
from selenium import webdriver
cookielist = open('cookietest.csv')
cookiereader = csv.reader(cookielist)
cookiedata = list(cookiereader)
curcookie = cookiedata[0][0]
driver=webdriver.Chrome()
driver.get("https://stackoverflow.com/")
driver.add_cookie(curcookie)

Does anyone have any ideas as to what I am doing wrong?

Thanks!

Upvotes: 0

Views: 8250

Answers (1)

Mike67
Mike67

Reputation: 11342

The cookie data is a list of dictionaries so json is the preferred file format.

Here is the code:

from selenium import webdriver
import json

print('get cookie')

driver=webdriver.Chrome()
driver.get("https://stackoverflow.com/")
cookies = driver.get_cookies()
with open('cookietest.json', 'w', newline='') as outputdata:
    json.dump(cookies, outputdata)

print('send cookie')

import json
from selenium import webdriver
with open('cookietest.json', 'r', newline='') as inputdata:
    cookies = json.load(inputdata)
curcookie = cookies[0]
driver=webdriver.Chrome()
driver.get("https://stackoverflow.com/")
driver.add_cookie(curcookie)

Here is the cookie json file (formatted, truncated)

[
    {
        "domain": ".stackoverflow.com",
        "expiry": 1629684418,
        "httpOnly": false,
        "name": "__qca",
        "path": "/",
        "secure": false,
        "value": "P0-1270404352-1595815618103"
    },
    {
        "domain": ".stackoverflow.com",
        "expiry": 1595815677,
        "httpOnly": false,
        "name": "_gat",
        "path": "/",
        "secure": false,
        "value": "1"
    },
    .........
]

Upvotes: 1

Related Questions