top of page
Writer's pictureshalissweet

Difference between findElement and findElements in Selenium WebDriver

In Automation to perform any operations on any elements, first we need to find the element. Only after finding the element we can perform the operation. To find the element, Selenium webdriver is providing two methods findelement and findelements. In this blog lets see the difference between these 2 methods and which method to use on what scenarios.



The difference between find Element and find Elements in Selenium WebDriver






FindElement:


· Find the first WebElement using the given method.

· This method is affected by the 'implicit wait' times 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.

· findElement should not be used to look for non-present elements, use findElements(By)and assert zero-length response instead.


FindElements:

· Find all elements within the current page using the given mechanism.

· This method is affected by the 'implicit wait' times in force at the time of execution.

· When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection or will return an empty list if the timeout is reached.


Lets see an example:



FindElement method returns the first matching element on the current webpage. If the element is not found then it throws an exception i.e. NoSuchElementException.


Syntax for FindElement

//FindElement
WebElement firstNameTxt = driver.findElement(By.xpath('//input[@name='name']));
firstNameTxt.sendkeys("HYR Tutorials");


If I need all the contact names & links from the table, all the buttons present in the green box in such case I need to get all the elements. Each contact name is present inside the table cell, so I need to get all the table cells and I need to iterate each table cell in that case I need to get the text of the table cell so we are dealing with multiple elements. Suppose if I want all the buttons and I want to see how many buttons are there I need to know the count. In this scenario we are handling multiple elements hence we will use findelements method



FindElements method returns all the matching elements on the current webpage and it doesn’t throw any exception if the element is not found, instead it will return zero elements.


Syntax for FindElements

//FindElements
List<WebElement> elements = driver.findElements(By.xpath("//div/h1));
System.out.println(elements.size());
for(WebElement element : elements)
{ 
            system.out.println (element.getText());
}



Hope this blog was useful !!!!


373 views

Recent Posts

See All
bottom of page