The List<WebElement> class in Selenium WebDriver is a powerful tool that enables you to easily and quickly manipulate web elements on a web page. With the help of List<WebElement>, you can access, modify, and interact with web elements such as buttons, links, images, tables, and more.
To use List<WebElement> in Selenium WebDriver, you first need to locate the elements on the page using the findElement() and findElements() methods. You can then store the elements in a List<WebElement> object.
Later use the List<WebElement> methods to access and manipulate the web elements.
For example,
- We can use List<WebElement>.get(index) to get a specific element based on its index in the list.
- We can also use List<WebElement>.size() to get the number of elements stored in the list. This is useful for looping through the list and performing certain actions on each element.
Code Sample:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ListWebElementExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Path to chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
//Find list of web elements
List<WebElement> listElements = driver.findElements(By.tagName("a"));
System.out.println("Total number of elements present : "+listElements.size());
//Iterate through the list and print the text of each element
for(int i=0; i<listElements.size(); i++)
{
System.out.println(listElements.get(i).getText());
}
driver.quit();
}
}