boolean isElementVisible = driver.findElement(By.id(“myHeaderDiv”)).isDisplayed(); is giving NoSuchElement Exception

28 views Asked by At

Hi I am writing a script wherein I need to check if the element is present or not? However, when the element is not present then the following code is giving me org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: Is not the method suppose to return false if the element is not visible or no such element exists?

    boolean isElementVisible = driver.findElement(By.id(“myHeaderDiv”)).isDisplayed();
if (isElementVisible) {
    return true;
}else{
    System.out.println("Is visible");
}
1

There are 1 answers

0
smallpepperz On

In Selenium for Java, if an element cannot be found, driver.findElement(...) will throw a NoSuchElementException. What you're seeing is the documented and intended behavior. Because the exception is thrown, your code does not continue, and .isDisplayed() is never evaluated. If you want to handle this case, you can use driver.findElements(...) and check the resulting size

List<WebElement> elements = driver.findElements(By.id("..."))
if (!elements.isEmpty() && elements.get(0).isDisplayed()) {
    System.out.println("element visible")
} else {
    System.out.println("element not visible")
}