在Selenium Webdriver中捕获用户生成的事件 [英] Catching user-generated events in selenium webdriver

查看:388
本文介绍了在Selenium Webdriver中捕获用户生成的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以捕获用户生成的Selenium WebDriver事件(或一般事件)吗?我知道我们可以检查页面f.e.的状态与 WebDriverWait ExpectedConditions ,但这并不总是适当的.

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();

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? */);
}

有什么办法吗?

推荐答案

我从没听说过Selenium支持它.但是,您可以通过在文档中添加一个eventListener来创建或更改DOM来自己制作.然后,您可以使用Selenium来检测更改.参见下面的示例.

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.

该示例使用JavaScript Executor将keydown侦听器添加到文档中.当按下键Enter时,它将创建一个ID为onEnter的div,然后将其添加到DOM中.最后,Selenium将查找ID为onEnter的元素,然后单击Web中的链接.

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);

这篇关于在Selenium Webdriver中捕获用户生成的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆