Chrome 的当前驱动程序(2.30 版)实现了以前的协议,其中仅支持修改键(Control、Shift、Alt、Command)按住键。
因此,此代码适用于 Firefox,但适用于 Chrome,因为keyUp
每个事件都会发出keyDown
:
action_key_down_w = ActionChains(driver).key_down("w")
action_key_up_w = ActionChains(driver).key_up("w")
endtime = time.time() + 1.0
while True:
action_key_down_w.perform()
if time.time() > endtime:
action_key_up_w.perform()
break
但是,从 2.30 版本开始,Chrome 驱动程序支持send_command
通过 devtools 协议直接发送原始命令。因此,作为一种解决方法,您可以调用Input.dispatchKeyEvent来发出低级事件。
这是一个使用 Selenium/Chromew
在一秒钟内保持密钥的工作示例:
from selenium import webdriver
import json, time
def dispatchKeyEvent(driver, name, options = {}):
options["type"] = name
body = json.dumps({'cmd': 'Input.dispatchKeyEvent', 'params': options})
resource = "/session/%s/chromium/send_command" % driver.session_id
url = driver.command_executor._url + resource
driver.command_executor._request('POST', url, body)
def holdKeyW(driver, duration):
endtime = time.time() + duration
options = { \
"code": "KeyW",
"key": "w",
"text": "w",
"unmodifiedText": "w",
"nativeVirtualKeyCode": ord("W"),
"windowsVirtualKeyCode": ord("W")
}
while True:
dispatchKeyEvent(driver, "rawKeyDown", options)
dispatchKeyEvent(driver, "char", options)
if time.time() > endtime:
dispatchKeyEvent(driver, "keyUp", options)
break
options["autoRepeat"] = True
time.sleep(0.01)
driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/questions")
# set the focus on the targeted element
driver.find_element_by_css_selector("input[name=q]").click()
# press the key W during a second
holdKeyW(driver, 1.0)