使用Selenium WebDriver和java检查该元素不存在的最佳方法

Rom*_*hin 20 java verify assertion selenium-webdriver

我尝试下面的代码,但似乎它不起作用...有人能告诉我最好的方法吗?

public void verifyThatCommentDeleted(final String text) throws Exception {
    new WebDriverWait(driver, 5).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                try {
                    input.findElement(By.xpath(String.format(
                            Locators.CHECK_TEXT_IN_FIRST_STATUS_BOX, text)));
                    return false;
                } catch (NoSuchElementException e) {
                    return true;
                }
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

Xol*_*.io 37

而不是使用findElement,执行findElements并检查返回元素的长度为0.这就是我使用WebdriverJS的方式,我希望它在Java中也能正常工作

  • 实际上,这也是官方文档推荐的内容:_"findElement不应该用于查找不存在的元素,而是使用findElements(By)并断言零长度响应."_ [Javadoc for WebElement#findElement](http: //selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#findElement%28org.openqa.selenium.By%29) (7认同)
  • 是的,这是官方的方法,但不幸的是[文档](https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebElement.html#findElements-org.openqa.selenium .By-) 还说:*“此方法受到执行时有效的‘隐式等待’时间的影响。”* 因此,您最终可能会做类似 ```driver.manage.timeouts.implicitlyWait( 10、TimeUnit.MILLISECONDS)```(也许用 ```finally``` 来再次重置超时)。 (2认同)

eug*_*kov 26

我通常使用几种方法(成对)来验证元素是否存在:

public boolean isElementPresent(By locatorKey) {
    try {
        driver.findElement(locatorKey);
        return true;
    } catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
    }
}

public boolean isElementVisible(String cssLocator){
    return driver.findElement(By.cssSelector(cssLocator)).isDisplayed();
}
Run Code Online (Sandbox Code Playgroud)

请注意,有时selenium可以在DOM中找到元素,但它们可能是不可见的,因此selenium将无法与它们进行交互.因此在这种情况下检查可见性的方法有帮助.

如果你想等待元素,直到它出现,我发现最好的解决方案是使用流畅的等待:

public WebElement fluentWait(final By locator){
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(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)

希望这可以帮助)


小智 6

使用findElements而不是findElement

如果没有找到匹配的元素而不是异常,findElements将返回一个空列表。此外,我们可以确保该元素是否存在。

例如:列表元素 = driver.findElements(By.yourlocatorstrategy);

if(elements.size()>0){
    do this..
 } else {
    do that..
 }
Run Code Online (Sandbox Code Playgroud)