How to get text from Selenium element WebElement object?

We can get text from a webelement with Selenium webdriver. The getText() methods obtains the innerText of an element. It fetches the text of an element which is visible along with its sub elements. It ignores the trailing and leading spaces.

First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css and then apply getText() method on it to get the text content of the element.

Let us get the text of the element About Careers at Tutorials on the page−


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;

public class GetElementText{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement p=driver.findElement(By.xpath("//h1"));
      //getText() to obtain text
      String s= p.getText();
      System.out.println("Text content is : " + s);