[英]How can I simulate key events with selenium in a CodeMirror Editor
There are plenty of examples around that show how to use the following to enter text using selenium周围有很多示例说明如何使用以下内容使用 selenium 输入文本
driver.execute_script('cm.setValue("text")');
This works, but isn't very "selenium" of us.这有效,但不是我们的“硒”。 We want to simulate actual keyboard key presses like the send_keys function in selenium.
我们想模拟实际的键盘按键,就像 selenium 中的 send_keys 函数一样。 We created a enterFormData that gets an element and types to it using driver.send_keys() (eg a textarea with an ID we can easily simulate typing) .
我们创建了一个enterFormData ,它使用 driver.send_keys() 获取一个元素并输入它(例如,一个带有 ID 的文本区域,我们可以很容易地模拟输入) 。 How can we simulate actual key presses into the CodeMirror editor?
我们如何在 CodeMirror 编辑器中模拟实际的按键操作? We also want to be able to test HotKeys (eg Ctrl-Shift-M) and then take a driver.get_screenshot_as_base64()
我们还希望能够测试热键(例如 Ctrl-Shift-M) ,然后使用driver.get_screenshot_as_base64()
For selenium to detect the keyboard events, you'll first have to bring codemirror into focus.要使 selenium 检测键盘事件,您首先必须使 codemirror 成为焦点。
You can do something like this:你可以这样做:
/* getting codemirror element */
WebElement codeMirror = driver.findElement(By.className("CodeMirror"));
/* getting the first line of code inside codemirror and clicking it to bring it in focus */
WebElement codeLine = codeMirror.findElements(By.className("CodeMirror-line")).get(0);
codeLine.click();
/* sending keystokes to textarea once codemirror is in focus */
WebElement txtbx = codeMirror.findElement(By.cssSelector("textarea"));
txtbx.sendKeys("Hello World");
The codemirror instance should have a hidden textarea in it which captures the keyboard events... codemirror 实例中应该有一个隐藏的 textarea 来捕获键盘事件...
I did something like this:我做了这样的事情:
driver.findElement(By.css('.CodeMirror textarea'))
.sendKeys('text',
webdriver.Key.chord(webdriver.Key.CONTROL, webdriver.Key.SHIFT, "m"));
This bit: webdriver.Key.chord(webdriver.Key.CONTROL, webdriver.Key.SHIFT, "m")
simulates the (Ctrl+Shift+M)这一点:
webdriver.Key.chord(webdriver.Key.CONTROL, webdriver.Key.SHIFT, "m")
模拟了 (Ctrl+Shift+M)
I myself have found this answer to the question https://stackoverflow.com/a/48969245/6077069 .我自己找到了这个问题的答案https://stackoverflow.com/a/48969245/6077069 。 You should use driver's action chains instead of element send_keys.
您应该使用驱动程序的操作链而不是元素 send_keys。 This is working in my case.
这在我的情况下有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.