I am trying to add a list of cookies to a selenium chrome instance running remotely, the singular method add_cookie is too slow for my needs with each request taking ~5-10 seconds and roughly 1000-5000 cookies this would become intractable. I have thought of creating a custom Cookie input to the ActionsChains class as follows:
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.input_device import InputDevice
from selenium.webdriver.common.actions.interaction import (Interaction, Pause)
class CookieInput(InputDevice):
def __init__(self, name):
super(CookieInput, self).__init__()
self.name = name
self.type = interaction.KEY
def encode(self):
return {"type": self.type, "id": self.name, "actions": [acts.encode() for acts in self.actions]}
def create_add_cookie(self, cookie):
self.add_action(CookieInteraction(self, "addCookie", cookie))
def create_delete_cookie(self, cookie):
self.add_action(CookieInteraction(self, "deleteCookie", cookie))
class CookieInteraction(Interaction):
def __init__(self, source, type_, cookie):
super(CookieInteraction, self).__init__(source)
self.type = type_
self.cookie = cookie
def encode(self):
return {"type": self.type, "value": self.cookie}
class CookieActions(Interaction):
def __init__(self, source):
if not source:
source = CookieInput(KEY)
self.source = source
super(CookieActions, self).__init__(source)
def add_cookie(self, cookie):
return self._cookie_action("create_add_cookie", cookie)
def delete_cookie(self, cookie):
return self._cookie_action("create_add_cookie", cookie)
def add_cookies(self, cookies):
for cookie in cookies:
self.add_cookie(cookie)
return self
def delete_cookies(self, cookies):
for cookie in cookies:
self.delete_cookie(cookie)
return self
def _cookie_action(self, action, cookie):
meth = getattr(self.source, action)
meth(cookie)
return self
which should be used as follows:
actions = ActionChains(driver)
cookiedevice = CookieInput("cookies")
actions.w3c_actions.devices.append(cookiedevice)
actions.w3c_actions.cookie_action = CookieActions(cookiedevice)
[actions.w3c_actions.cookie_action.add_cookie(c) for c in cookies]
actions.perform()
This throws the analogous error:
InvalidArgumentException: Message: invalid argument from invalid argument: type of action must be the string 'keyUp', 'keyDown' or 'pause' (Session info: chrome=91.0.4472.77)
This is obviously an error from the chrome driver itself. Is there a more straight forward method of implementing this logic than rolling out a custom chrome driver implementation? Thanks, Best Regards.