Best way to check that element is not present using Selenium WebDriver with java

后端 未结 9 1968
半阙折子戏
半阙折子戏 2020-12-24 02:33

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         


        
9条回答
  •  一向
    一向 (楼主)
    2020-12-24 03:06

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

    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 wait = new FluentWait(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);
    
        WebElement foo = wait.until(new Function() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(locator);
            }
        });
    
        return foo;
    };
    

    Hope this helps)

提交回复
热议问题