Selenium webdriver provides two methods for finding webelements on a webpage – driver.findElement() and driver.findElements(). In this post, we will study the difference between the two and also see where to use them effectively.
|Definition||driver.findElement() is used to find a webElement on a webpage.||driver.findElements() is used to find a List of webElements matching the locator passed as parameter.|
|Syntax||WebElement element = driver.findElement(By locator);||List<WebElement> elements = driver.findElements(By locator);|
|For multiple matches||In case the same locator matches multiple webElements then findElement method returns the first web element found.||In case of multiple matches the findElements method returns a list of webElements. For interacting with a particular element we have find the particular element by its index e.g. elements.get(0).click(); will perform the click operation on the first element of the ‘elements’ list.|
|If no element is found||In case the locator passed to findElement() method leads to no element then NoSuchElementException is thrown.||In case the locator passed to findElements() method leads to no element then a List of 0 size is returned instead of an exception.|
Please note that because of the fact that in case no element is found driver.findElements() return a list of size 0 (unlike findElement() that throws exception), it is generally used to check for the presence of an element. We can just check the size of the list returned by findElements() method and if its non-zero, we can interact with the first element of the list using 0 index.
check our complete step-by-step selenium tutorial here.
Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals. You can find him on LinkedIn and also follow ArtOfTesting’s LinkedIn page.