When to use findElements() method in selenium webdriver

findElements method is different than the findElement method in selenium webdriver. findElements method is useful to find all elements from page using given element locator strategies.You can locate all specific elements from page using class name, css selector, id, name, link text, partial link text, tag name or xpath. findElements will return list of web elements using given locator strategy and then you can iterate through list and perform action. Lets see how it works.


How findElements() Works?
package TestPack;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class testFindElements {

 public static void main(String[] args) throws InterruptedException {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("https://only-testing-blog.blogspot.com/2015/01/table-with-checkbox.html");
  
  //Find all checkbox from page using findElements method
  List<WebElement> listOfElements = driver.findElements(By.tagName("input"));
  
  //Check all checkbox one by one
  for(WebElement checkBox:listOfElements)
     {
   Thread.sleep(1000);
         checkBox.click(); 
     }

 }

}

Result : It will locate all checkbox from page using findElements() and select them one by one.


When you need findElements() method?
In above example you can see that we have located all elements from page with tagName("input") using findElements() and stored it in to the list. Then iterated through list to select all of them one by one. HTML unique Ids and well-written CSS selector are preferred ways to use with findElements() method to locate elements.

No comments:

Post a Comment