使用带有 Java 的 Selenium WebDriver 检查元素不存在的最佳方法 [英] Best way to check that element is not present using Selenium WebDriver with java

查看:37
本文介绍了使用带有 Java 的 Selenium WebDriver 检查元素不存在的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying the code below but it seems it does not work... Can someone show me the best way to do this?

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

推荐答案

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

i usually couple of methods (in pair) for verification whether element is present or not:

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

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

Note that sometimes selenium can find elements in DOM but they can be invisible, consequently selenium will not be able to interact with them. So in this case method checking for visibility helps.

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

If you want to wait for the element until it appears the best solution i found is to use fluent wait:

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

希望这有帮助)

这篇关于使用带有 Java 的 Selenium WebDriver 检查元素不存在的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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