简体   繁体   English

在Selenium Webdriver中捕获用户生成的事件

[英]Catching user-generated events in selenium webdriver

Can we catch in Selenium WebDriver events generated by the user (or events in general)? 我们可以捕获用户生成的Selenium WebDriver事件(或一般事件)吗? I know we can check state of page fe with WebDriverWait and ExpectedConditions , but that is not always appropriate. 我知道我们可以使用WebDriverWaitExpectedConditions检查fe页面的状态,但这并不总是合适的。

Let's say I wanted to wait for user input to continue execution of test class. 假设我想等待用户输入继续执行测试类。 It would look something like this: 它看起来像这样:

driver.get("https://www.google.com");

waitForKey(driver, org.openqa.selenium.Keys.RETURN);

/* rest of code */

driver.quit();

Where waitForKey would be implemented as: 其中waitForKey将实现为:

public static void waitForKey(WebDriver driver, org.openqa.selenium.Keys key) {
     Wait wait = new WebDriverWait(driver, 2147483647);
     wait.until((WebDriver dr) -> /* what should be here? */);
}

Is there any way to do this? 有什么办法吗?

I never heard that Selenium support it. 我从未听说过Selenium支持它。 However, you can make it yourself by adding an eventListener to the document to create or change DOM. 但是,您可以通过在文档中添加一个eventListener来创建或更改DOM来自己制作。 Then you can use Selenium to detect the change. 然后,您可以使用Selenium来检测更改。 See my example below. 请参阅下面的示例。

The example uses JavaScript Executor to add a keydown listener to the document. 该示例使用JavaScript Executor将keydown侦听器添加到文档中。 When the key Enter has been pressed, it will create a div with ID onEnter and then add it to the DOM. 按下Enter键后,它将创建一个ID为onEnter的div,然后将其添加到DOM中。 Finally, Selenium will looking for the element with ID onEnter , and then it will click a link in the web. 最后,Selenium将查找ID为onEnter的元素,然后单击Web中的链接。

driver.get("http://buaban.com");
Thread.sleep(5000);
String script = "document.addEventListener('keydown', function keyDownHandler(event) {" + 
                "    const keyName = event.key;" + 
                "    if(keyName===\"Enter\") {" +
                "        var newdiv = document.createElement('DIV');" +
                "        newdiv.id = 'onEnter';"+
                "        newdiv.style.display = 'none';"+
                "        document.body.appendChild(newdiv);" +
                "    }" +
                "});";

((JavascriptExecutor)driver).executeScript(script);

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("onEnter")));
driver.findElement(By.cssSelector("#menu-post a")).click();
Thread.sleep(5000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM