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.

Syntax

List<WebElement> m =
driver.findElements(By.xpath("//h2[@class='store-name']"));

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 ElementsSameclsname{
   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.justdial.com/Bangalore/Bakeries");
      // 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);
      }
      driver.quit();
   }
}

Output

Updated on: 03-Apr-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements