How to get the text from a website using selenium?


We can get the text from a website using Selenium webdriver USING the getText method. It helps to obtain the text for a particular element which is visible or the inner text (which is not concealed from the page).

First of all, we have to identify the element on the page for which we want to get the text with the help of any locators like id, class, name, xpath, css, tag name, link text or partial link text.

Let us try to retrieve the text - ENJOY PREMIUM CONTENT AT AFFORDABLE PRICE from the below page −

Syntax

WebElement n =driver.findElement(By.tagName("h2"));
String s = n.getText();

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ElementTxt{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element with tagname
      WebElement s = driver.findElement(By.tagName("h2"));
      // obtain element text
      String st = s.getText();
      System.out.println("Text is : " + st);
      driver.quit();
   }
}

Output

Updated on: 06-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements