Get Visible Text of Element

To get the visible text of a web element programmatically using Selenium in Java, call getText() method on the web element.

We have to first find the web element by name, id, class name, or any of the locator, and then call the getText() function on this web element. getText() method returns the visible text for this web element as a String.

The following is a simple code snippet where we find the first link element and then get the visible text for this link element using getText().

WebElement link = driver.findElement(By.tagName("a"));
String text = link.getText();
ADVERTISEMENT

Example

In the following program, we write Java code to find the first link element (tagName=”a”), get its visible text value, and print the text value to console output.

Java Program

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

import java.time.Duration;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

        WebElement link = driver.findElement(By.tagName("a"));
        String text = link.getText();
        System.out.println("Visible Text : " + text);

        driver.quit();
    }
}

Output

Visible Text : Gmail