Find an Element Using XPath in Selenium



We can find an element using the xpath locator with Selenium webdriver.

To identify the element with xpath, the expression should be //tagname[@attribute='value'].

To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify.

For example,

/html/body/div[1]/div/div[1]/a

The relative xpath begins with // symbol and does not start from the root node. For example,

//img[@alt='tutorialspoint']

Let us see the html code of the highlighted element starting from the root.

The absolute xpath for the element Home is /html/body/div[1]/div/div[1]/a.

The relative xpath for element Home is //a[@title='TutorialsPoint - Home'].

There are also functions available which help to frame relative xpath expressions −

  • text() – It is used to identify an element with the help of the visible text on the page. The xpath expression is //*[text()='Home'].

  • starts-with – It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load.

Let us see the html of the element Q/A −

The xpath expression should be //a[starts-with(@title, 'Questions &')].

  • contains() - it identifies an element whose attribute value contains a sub-text of the actual attribute value. This function is normally used for attributes whose value changes on each page load.

The xpath expression is : //a[contains(@title, 'Questions & Answers')].

Syntax

WebElement m = driver.findElement(By.xpath("//span[@class = 'cat-title']"));

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 LocatorXpath{
   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/online_dev_tools.htm");
      // identify element with xpath
      WebElement n=driver.
      findElement(By.xpath("//span[@class = 'cat-title']"));
      String str = n.getText();
      System.out.println("Text is : " + str);
      driver.close();
   }
}

Output

Updated on: 2021-04-06T08:44:11+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements