Catching user-generated events in selenium webdriver

偶尔善良 提交于 2019-12-08 11:54:10

问题


Can we catch in Selenium WebDriver events generated by the user (or events in general)? I know we can check state of page f.e. with WebDriverWait and ExpectedConditions, but that is not always appropriate.

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:

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?


回答1:


I never heard that Selenium support it. However, you can make it yourself by adding an eventListener to the document to create or change DOM. Then you can use Selenium to detect the change. See my example below.

The example uses JavaScript Executor to add a keydown listener to the document. When the key Enter has been pressed, it will create a div with ID onEnter and then add it to the DOM. Finally, Selenium will looking for the element with ID onEnter, and then it will click a link in the 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);


来源:https://stackoverflow.com/questions/48476518/catching-user-generated-events-in-selenium-webdriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!