
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Text from List of 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
Advertisements