How to print text from a list of all web elements with same class name in Selenium?

We can get the text from a list of all web elements with the same class name in Selenium webdriver. We can use any of the locators like the class name with method By.className, xpath with method By.xpath, or css with method By.cssSelector.

Let us verify a xpath expression //h2[@class='store-name'] which represents multiple elements that have the same class name as store-name. If we validate this in Console with the expression - $x("//h2[@class='store-name']"), it yields all the matching elements as shown below:

Also, since we need to obtain multiple elements, we have to use the findElements method which returns a list. We shall iterate through this list and obtain the text of the elements with getText method.


List<WebElement> m =


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ElementsSameclsname{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // identify elements list with same class name
      List<WebElement> m = driver.findElements(By.xpath("//h2[@class='store-name']"));
      // iterate over list
      for(int i = 0; i< m.size(); i++) {
         //obtain text
         String s = m.get(i).getText();
         System.out.println("Text is: " + s);