user7309686
user7309686

Reputation: 79

NoSuchElementException with isDisplayed() method within try catch block in Selenium

i want to check negative condition. above boolean element is not displayed ,but i have to print true and false but it shows no such element exception please help.

try{

    boolean k= driver.findElement(By.xpath("xpath_of_element")).isDisplayed();
    if(!k==true)
    {
             System.out.println("true12"); 
    }

}catch (NoSuchElementException e) {
    System.out.println(e);
}

Upvotes: 1

Views: 10144

Answers (3)

Powiadam Cię
Powiadam Cię

Reputation: 159

        if (driver.findElements(xpath_of_element).size() != 0) return true;
        return false;

Upvotes: 0

JaySin
JaySin

Reputation: 13

You should use the below code which will validate if at least one or more than one elements are present or not for the given xpath, before checking for the display status of the element.

List<WebElement> targetElement =  driver.findElements(By.xpath("xpath_your_expected_element"));
    try {
        if(targetElement>=1) {
            if(targetElement.isDisplayed()) {
                System.out.println("Element is present");
            }
            else {
                System.out.println("Element is found, but hidden on the page");
            }
            else {
                System.out.println("Element not found on the page");
            }
        }catch (NoSuchElementException e) {
            System.out.println("Exception in finding the element:" + e.getMessage());
        }

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193308

There are two distinct stages of an element as follows:

  • Element present within the HTML DOM
  • Element visible i.e. displayed within the DOM Tree

As you are seeing NoSuchElementException which essentially indicates that the element is not present within the Viewport and in all possible conditions isDisplayed() method will return false. So to validate both the conditions you can use the following solution:

try{
    if(driver.findElement(By.xpath("xpath_of_the_desired_element")).isDisplayed())
        System.out.println("Element is present and displayed");
    else
        System.out.println("Element is present but not displayed"); 
}catch (NoSuchElementException e) {
    System.out.println("Element is not present, hence not displayed as well");
}

Upvotes: 4

Related Questions