In this post, we will go through the differences between findElements and findElement methods of Selenium Webdriver. This question is often asked in the testing interviews for Webdriver automation testers. Both the methods use By locating mechanism
Find all elements within the current page using the given mechanism. This method returns List so it may return zero or more Web elements. Note that if locating mechanism from By instance doesn’t find any findElements() method returns an empty list. In day-to-day Webdriver programming it is often we use these two methods.
List<WebElement> findElements(By by);
Sample example of finding the links on a web page is as shown below code snippet :
List<WebElement> links = driver.findElements(By.tagName("a"));
In the above example, the method returned a List<WebElement>. This method is affected by the implicit wait times in force at the time of execution. When we use implicitly wait this method will return items found in the collection.At last if the timeout is reached it will return an empty list.
findElement() returns the first matching element on the current page. The method NoSuchElementException ,ff no matching elements are found.
WebElement findElement(By by);
This method is affected by the implicit wait time in force at the time of execution. The findElement() invocation will return a matching row, or try again repeatedly until the configured timeout is reached.
Sample example of the method used as shown below snippet:
driver.get("https://www.bing.com/"); WebElement element = driver.findElement(By.id("sb_form_q"));
In the above example, the method returned a WebElement.In addition, when you are testing for non-existing elements on the web page, it is a best practice not to use this method.It’s always better to use findElements() method .findElement() should not be used to look for non-present elements on the page , use findElements() and assert zero-length response instead.