“invalid argument: invalid 'expiry'”
I'm trying to add cookies to a browser, but getting the following error:
How to fix “invalid argument: invalid 'expiry'” in Selenium when adding cookies to a chromedriver?
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
driver.get ( URL )
sleep ( 2 )
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
sleep(2)
driver.get ( URL )
print(driver.get_cookies())
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
Error msg
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid 'expiry'
(Session info: chrome=75.0.3770.100)
first of all follow link from comment to change pickle to dict
see also this
https://www.w3.org/TR/webdriver/#add-cookie point 6
expiry should be now int
not float
.
for cookie in cookies:
if isinstance(cookie.get('expiry'), float):
cookie['expiry'] = int(cookie['expiry'])
driver.add_cookie(cookie)
The reason the 'expiry' values are being rejected by newer versions of chromedriver is because of this change: https://chromium.googlesource.com/chromium/src/+/c83119b466cfd63fd1eb616ee86b22ede5db3c4e%5E%21/#F4
When your chromedriver is in w3c compliant mode, it now requires that 'expiry' be an int64, whereas in legacy mode it will continue to accept the old float values.
The problem (and it may be a bug in chromedriver), is that driver.get_cookies()
continues to return 'expiry' values as floats, while driver.add_cookie(...)
does not accept these cookies back.
So to get around this for now, you have two options:
- Convert your expiry keys to an integer (multiply them by 1000 to get milliseconds):
cookie["expiry"] = int(cookie["expiry"]*1000)
before passing them to driver.add_cookie(...)
OR
- Disable w3c compliance on your chromedriver session, by adding an experimental flag to ChromeOptions:
from selenium import webdriver
opt = webdriver.ChromeOptions()
opt.add_experimental_option('w3c', False)
driver = webdriver.Chrome(chrome_options=opt)
this issue has been fixed in ChromeDriver-83
and the version is released:
Resolved issue 3331: The get_cookies() method is returning 'expiry' keys of type double, but should be int64 in w3c mode