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')]").


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class FindElmntsText{
   public static void main(String[] args) {
      System.setProperty("",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element with text
      WebElement i=
      (By.xpath("//*[contains(text(), 'You are browsing')]"));
      // get text for element
      System.out.println("Text is: " + i.getText());