I know I could use (driver.findElements(By.xpath("Xpath Value")).size() != 0);
However, I am using a Page Object Model, who's entire purpose is to predefine the WebElements in a separate class, so I don't have to "FindElements By" in my test classes.
Here's what I currently have
if (objPage.webElement.isEnabled()){
System.out.println("found element");
}else{
System.out.println("element not found");
}
However, this tries to identify the possibly non-existent WebElement. When it is not present, I get:
No Such Element" exception.
isDisplayed() is the method used to verify a presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
The findElements gives an elements list. We shall count the number of elements returned by the list with the help of the size method. If the value of size is greater than 0, then the element exists and if it is lesser than 0, then the element does not exist.
isEnabled() Method in Selenium isEnabled() method is used to check if the web element is enabled or disabled within the web page. This method returns “true” value if the specified web element is enabled on the web page otherwise returns “false” value if the web element is disabled on the web page.
Selenium WebDriver defines two methods for identifying the elements, they are findElement and findElements . findElement: This command is used to uniquely identify a web element within the web page. findElements: This command is used to uniquely identify the list of web elements within the web page.
Best practice is to do what you originally suggested, use .findElements()
and check for .size != 0
or you can also use my preference, .isEmpty()
. You can create a Util function like the below to test if an element exists.
public boolean elementExists(By locator)
{
return !driver.findElements(locator).isEmpty();
}
You could also build this into a function in your page object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With