Check if an Element is Present on the Webpage

Check if an Element is Present on the Webpage

During automation, we quite frequently need to work with dynamic elements or elements which are not always available in the DOM and whose presence can be used as a medium of assertion to pass or fail a test case.

Cases like these require us to check for the presence of elements on the webpage. In this tutorial, we will use driver.findElements() method in Selenium WebDriver with Java to make sure, we interact with an element only if it is present on the web page.

Using driver.findElements()

In order to check if an element is present on a webpage, we make use of driver.findElements() method. As we know that driver.findElements() method returns a list of webElements located by the “By Locator” passed as parameter. If element is found then it returns a list of non-zero webElements else it returns a size 0 list. Thus, checking the size of the list can be used to check for the presence and absence of element.

List dynamicElement = driver.findElements(By.id("id"));
if(dynamicElement.size() != 0){
//If list size is non-zero, element is present
System.out.println("Element present");
}
else{
//Else if size is 0, then element is not present
System.out.println("Element not present");
}


Please note that this method will wait until the implicit wait specified for the driver while finding the element. So, in case we know that element will be at once present on the webpage than in order to speed up the process, we can set the implicit wait to 0 first, check for the presence of elements and then revert the value of implicit wait to its default value.

//Set implict wait to 0
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
//Check for element's presence
List dynamicElement = driver.findElements(By.id("id"));
if(dynamicElement.size() != 0)
System.out.println("Element present");
else
System.out.println("Element not present");
//Revert back to default value of implicit wait
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

Why not use driver.findElement()

You may ask, why can’t we directly use the driver.findElement() method here? The reason for not using findElement() method is, in case the element is not present then findElement() method will throw NoSuchElementException exception which we need to catch first and then in the catch block, we have to write the code to take further steps after knowing that the element is not present. Like this-

try{
driver.findElements(By.id("id"));
//Since, no exception, so element is present
System.out.println("Element present");
}
catch(NoSuchElementException e){
//Element is not present
System.out.println("Element not present");
}

But having business logic in the catch block is highly disregarded as it is not an optimized way and make use of additional resources. The bottom line here is – our code should not rely on any exception to perform the normal flow.

От QA genius

Adblock
detector