How to fix "invalid argument: invalid 'expiry'" in Selenium when adding cookies to a chromedriver?
In my case, the previous answer did not work. I had to remove the expire key from the object.
for cookie in pickle.load(open(PATH, "rb")):
if 'expiry' in cookie:
del cookie['expiry']
self.driver.add_cookie(cookie)
This happens if you previously pickled the cookies directly as they're returned from the driver, like so:
pickle.dump(browser.get_cookies(), open(PATH, "wb"))
In my version of python and selenium, I have found that on there is a difference between how Selenium outputs cookie expiry values and how it imports them. When you use
driver.get_cookies()
the driver can output expiry values that are floats rather than integers. These floats seem to be epoch time units (number of seconds since Jan 1, 1970). If you try to add these exact cookies back into driver, they will fail because the driver only accepts cookies with integer expiry values. In this line:
driver.add_cookie({'name': name, 'value': value, 'expiry': expiry})
the value of expiry MUST be an integer. Otherwise, you will get the value error. I fixed this using the following code.
# Saving current cookies and reformatting them
cookies = driver.get_cookies()
for cookie in cookies:
if 'expiry' in cookie:
cookie['expiry'] = int(cookie['expiry'])
# Adding cookies back into the driver
driver.add_cookie(cookie)
This worked for me, and I no longer get an error.
The problem is that you are trying to add the cookies with a different format than the selenium expects.
The python selenium api reference says that you have to insert the cookies with a dict like that
driver.add_cookie({'name' : 'foo', 'value' : 'bar'})
So you have to adapt your loop to use a key,value format
for key, value in pickle.load(open(r'{0}\{1}_cookie.pkl'.format(settings.COOKIES_PATH, self.tv_username), 'rb')):
self.browser.add_cookie({'name' : key, 'value' : value})