Find elements using Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can find elements using Selenium webdriver with the help of the findElements method. This can be applied to the locators like id, class, name, link text, partial link text, css, xpath and tagname.

The findElements method returns a list of elements which match with the locator (with the By object) passed as a parameter to the method. To count the number of elements returned by the list, the method size is used. If there are no matching elements, an empty list is returned.

The below image shows the list of methods available with findElements.

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 FindElmnts{
   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/index.htm");
      //identify elements with anchor tagname
      List e = driver.findElements(By.tagName("a"));
      //count matching elements with size
      int s = e.size();
      System.out.println("Number of matching elements: " + s);
      driver.quit();
   }
}

Output

raja
Published on 06-Apr-2021 08:00:11
Advertisements