Best Way To Check That Element Is Not Present Using Selenium WebDriver With Java


Answer :

Instead of doing findElement, do findElements and check the length of the returned elements is 0. This is how I'm doing using WebdriverJS and I expect the same will work in Java


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

Hope this helps)


Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception. Also, we can make sure that the element is present or not.

Ex: List elements = driver.findElements(By.yourlocatorstrategy);

if(elements.size()>0){     do this..  } else {     do that..  } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?