Selenium Get Text of Element

Profile picture for user arilio666

In this article, we will be seeing how we can get the text of an element using Selenium in Java; you can use the getText() method of the WebElement class.

For example:

WebElement element = driver.findElement(By.id("elementId"));
String text = element.getText();
System.out.println(text);
  • This will find the element with the ID "elementId" using the findElement method and store it as a WebElement object. Then, it calls the getText() method on that object and assigns the resulting text to the variable text. Finally, it prints out the text.
  • Note that this only works if the element is visible on the page and the text is inside the element's tags. If the element is hidden or the text is in an attribute, you may need to use a different method to retrieve it.

Let us try to fetch texts of all these elements at once.

        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.programsbuzz.com/");
        driver.manage().window().maximize();
        Thread.sleep(3000);
        List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
        for (WebElement webElement : elementTexts) {
            System.out.println(webElement.getText());
        }
  • We took the list of elements using findElements and then iterated using advanced for loop.
  • This will now yield texts within it iterated and ready for us.