Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a WebElement exists with Selenium?

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.

like image 612
dsidler Avatar asked Dec 13 '16 15:12

dsidler


People also ask

How you will identify presence of a WebElement?

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.

How do you check if element does not exist in Selenium?

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.

How do I check if WebElement is enabled in Selenium?

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.

Which is the best approach to identify a WebElement?

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.


1 Answers

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.

like image 80
JeffC Avatar answered Oct 17 '22 18:10

JeffC