During automation, we quite frequently need to work with dynamic elements or elements which are not always available in the DOM and who's 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 element on the webpage.
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 list can be used to check for the presence and absence of element.
Please note that this method will wait till 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 then in order to speed up the process, we can set the implcit wait to 0 first, check for the presence of element and then revert the value of implicit wait to its default value.
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-
But having business logic in catch block is highly disregarded as it is not an optimized way and make use of additional resources. Bottom line here is - our code should not rely on any exception to perform the normal flow.