Finding text on page with Selenium 2


We can find text on page with Selenium webdriver. First of all, we shall identify the element with the help of the locator xpath. In xpath, we can use the contains() and text() functions.

Let us find the below highlighted text on the page −

The xpath expression shall be //*[contains(text(),'You are browsing')]. To obtain the text of the element, the getText method is used. Let us check the xpath expression we have created from the Console tab with the expression: $x("//*[contains(text(),'You are browsing')]").

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;
public class FindElmntsText{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element with text
      WebElement i=
      driver.findElement
      (By.xpath("//*[contains(text(), 'You are browsing')]"));
      // get text for element
      System.out.println("Text is: " + i.getText());
   }
   driver.close();
}

Output

Updated on: 02-Feb-2021

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements