Selenium API不提供此功能。从官方文档中:
https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol
服务器必须按以下方式处理键序列:键盘上出现的每个不需要修改键的键都作为键按下(keydown)和键向上(key up)一起发送。
但是,您可以使用一段Javascript模拟按键事件:
const SIMULATE_KEY = "var e = new Event(arguments[0]);" + "e.key = arguments[1];" + "e.keyCode = e.key.charCodeAt(0);" + "e.which = e.keyCode;" + "e.altKey = false;" + "e.ctrlKey = false;" + "e.shiftKey = false;" + "e.metaKey = false;" + "e.bubbles = true;" + "arguments[2].dispatchEvent(e);";var target = driver.findElement(By.Id("..."));// press the key "a"browser.executescript(SIMULATE_KEY, "keydown", "a", target);// release the key "a"browser.executescript(SIMULATE_KEY, "keyup", "a", target);


