我正在尝试访问网页,将cookie保存到csv文件中,然后稍后将其与selenium和python一起使用。当前,我可以很好地保存cookie,但是后来当我尝试使用该cookie时,出现以下错误:
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: missing 'cookie'
(Session info: chrome=84.0.4147.89)
这是我保存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])
这是我的代码,以便使用Cookie加载网页:
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)
有人对我在做什么错有任何想法吗?
谢谢!
答案 0 :(得分:1)
cookie数据是词典列表,因此json是首选文件格式。
代码如下:
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)
这是cookie json文件(已格式化,已截断)
[
{
"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"
},
.........
]