Reputation: 79
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
Reputation: 159
if (driver.findElements(xpath_of_element).size() != 0) return true;
return false;
Upvotes: 0
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
Reputation: 193308
There are two distinct stages of an element as follows:
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