Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When do we use findElement() and findElements() in Selenium?
The methods findElements and findElement are used to identify elements on a webpage. While findElement can pinpoint only one element, the findElements method yields a list of matching web elements.
The return type of findElements is a list whereas the return type of findElement is a WebElement. If there is no matching element on the page, an exception is thrown by the findElement method. In this scenario, an empty list id returned by the findElements method.
A good example of findElements method usage is counting the total number of links or accessing each of links by iterating through the links.
Syntax
WebElement m = driver.findElement(By.linkText("Subject"));
List<WebElement> n =
driver.findElements(By.tagName("a"));
Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class FindElmntsvsFindElement{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm");
//identify an element with tagname
WebElement e = driver.findElement(By.tagName("h2"));
String str = e.getText();
System.out.println("Get text on element: " + str);
//identify elements with anchor image
List<WebElement> m = driver.findElements(By.tagName("img"));
//count images
int s = m.size();
System.out.println("Number of images: " + s);
driver.quit();
}
}
Output

Advertisements