在Selenium中避免NoSuchElementException的最佳方法是什么?

Par*_*ngh 21 java selenium-grid selenium-webdriver nosuchelementexception

我在Selenium WebDriver中使用Java编写了一些测试用例,并在网格(集线器和多个节点)上执行它们.我注意到一些测试用例由于失败而失败NoSuchElementException.什么是最好和最有效的方法来避免NoSuchElementException和确保始终找到元素?

Pet*_*sik 27

您永远无法确定是否会找到该元素,实际上这是功能测试的目的 - 告诉您页面上是否有任何更改.但有一两件事肯定是有帮助是添加等待这往往导致元素NoSuchElementException

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
Run Code Online (Sandbox Code Playgroud)


eug*_*kov 7

我完全同意上面的Petr Mensik.你永远不能说元素是否存在的问题.你应该清楚地了解它何时发生.根据我的经验,我应该说它是由于以下原因而发生的:

  • 1)页面仍在渲染中,您已经完成元素搜索并且没有获得元素异常.
  • 2)第二个原因是AJAX还没有返回,你已经获得了 NoSuchElementException
  • 3)第三个是最明显的:元素真的不在页面上.

因此,使用一个函数调用来处理所有这三个条件的最强大的IMHO方法是使用fluentWaitAmith003建议的.

所以代码如下:

让ur元素有定位器:

String elLocXpath= "..blablabla";
WebElement myButton= fluentWait(By.xpath(elLocXpath));
myButton.click();

public WebElement fluentWait(final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)

                .pollingEvery(5, TimeUnit.SECONDS)

        .ignoring(org.openqa.selenium.NoSuchElementException.class);
        WebElement foo = wait.until(
                new Function<WebDriver, WebElement>() {
                    public WebElement apply(WebDriver driver) {
                        return driver.findElement(locator);
                    }
                }
        );
        return  foo;
    };
Run Code Online (Sandbox Code Playgroud)

此外,如果你的目的是强大的代码包装fluentWait()try{} catch{}块.

也别忘了

 public boolean isElementPresent(By selector)
   {

              return driver.findElements(selector).size()>0;
}
Run Code Online (Sandbox Code Playgroud)

这也很有用.

因此,如果您想要避免NoElement异常,只需正确处理它就可以得出结论,因为没有人能够确保页面中的元素存在.

希望现在对你来说更清楚了.问候