我正在尝试将 cookie 列表添加到远程运行的 selenium chrome 实例中,单个方法 add_cookie 对我的需要来说太慢了,每个请求大约需要 5-10 秒,大约 1000-5000 个 cookie,这将变得难以处理。我曾想过为 ActionsChains 类创建一个自定义 Cookie 输入,如下所示:
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
应按如下方式使用:
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()
这会引发类似的错误:
InvalidArgumentException:消息:来自无效参数的无效参数:操作类型必须是字符串“keyUp”、“keyDown”或“pause”(会话信息:chrome=91.0.4472.77)
这显然是 chrome 驱动程序本身的错误。有没有比推出自定义 chrome 驱动程序实现更直接的方法来实现这个逻辑?谢谢,最好的问候。