How to find XPath

In Selenium automation, if the elements are not found by the general locators like id, class, name, etc. then XPath is used to find an element on the web page. Xpath is most common used locator technique if general locators cannot be used.

In this we would learn what is XPath and different ways to find complex or dynamic elements XPath whose attributes changes dynamically on refresh or any operations.

What is XPath in Selenium?

XPath in Selenium is an XML path used for navigation through the HTML structure of the page. It is a syntax or language for finding any element on a web page using XML path expression. XPath can be used for both HTML and XML documents to find the location of any element on a webpage using HTML DOM structure.

Syntax: - xpath = //tagname[@attribute=’value’]

  • // : Select current node.
  • Tagname: Tagname of the particular node.
  • @: Select attribute.
  • Attribute: Attribute name of the node.
  • Value: Value of the attribute.

 Types of X-Path

There are basically two types of XPath

  • Absolute Xpath
  • Relative Xpath
Absolute XPath:

Absolute Xpath starts with root node, it starts from <html> tag till the node whose web element needs to be located. It starts from single slash(/)

Example:

xpath = html/head/body/form/table/tbody/tr/th

Now using the above xpath we can locate the web element and perform actions on that elements.

driver.findElement(By.xpath(“html/head/body/form/table/tbody/tr/th”)).click();

Let us consider example of Absolute XPath.

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AbsoluteXPath {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//code to maximize chrome browser
driver.manage().window().maximize();

String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
driver.get(baseURL);

//code to send values to edit box using absolute Xpath
driver.findElement(By.xpath
("/html[1]/body[1]/div[2]/div[3]/fieldset[1]/input[1]")).sendKeys("Rahul Shetty");

//Close chrome driver.
driver.close();
}
}

The only and major drawback of Absolute XPath is if something is changed in between than it is difficult to identify the change and need to make changes every time if changes are made in DOM, due to this it is difficult to maintain code with Absolute XPath.

Relative Xpath

A relative xpath is one where the path starts from the node of your choice. it does not need to start from the root node. It starts with Double forward slash(//). Relative Xpath is always preferred as it is not a complete path from the root element.

Example:

Xpath = //*[@id=’login’]/ul/li[3]/a

Now using the above xpath we can locate the web element and perform actions on that elements.

driver.findElement(By.xpath(“//*[@id=’login’]/ul/li[3]/a”)).click();

Let us consider example of Absolute XPath

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RelativeXpath {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//code to maximize chrome browser
driver.manage().window().maximize();

String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
driver.get(baseURL);

//code to send values to edit box using relative Xpath
driver.findElement(By.xpath("//input[@id='name']")).sendKeys("Rahul Shetty");

//Close chrome driver.
driver.close();
}
}

What are XPath axes.

XPath axes search different nodes in XML document from current context node. XPath Axes are the methods used to find dynamic elements, which otherwise not possible by normal XPath method having no ID , Classname, Name, etc.

Axes methods are used to find those elements, which dynamically change on refresh or any other operations. There are few axes methods commonly used in Selenium Webdriver like child, parent, ancestor, sibling, preceding, self, etc.

Using XPath Handling complex & dynamic elements in Selenium

1) Basic XPath:

XPath expression select node or list of nodes based on attributes like ID, Name, Classname etc. from DOM of the web element.

Syntax: - xpath = //tagname[@attribute=’value’]

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RelativeXpath {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        //code to maximize chrome browser
        driver.manage().window().maximize();

        String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
        driver.get(baseURL);

        //code to send values to edit box using relative Xpath
        driver.findElement(By.xpath("//input[@id='name']")).sendKeys("Rahul Shetty");

        //Close chrome driver.
        driver.close();
    }
}

Some more example of basic XPath expression.

Xpath = //input[@name=’ enter-name’]

Xpath = //input[@class=’ btn-style’]

Xpath = //input[@type=’submit’]

2) Contains():

Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically, for example, login information.

The contain feature has an ability to find the element with partial text as shown in below XPath example.

In this example, we tried to identify the element by just using partial text value of the attribute. In the below XPath expression partial value 'sub' is used in place of submit button. It can be observed that the element is found successfully.

Complete value of 'Type' is 'submit' but using only partial value 'sub'.

Xpath = //*[contains(@type,’sub’)]

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RelativeXpath {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        //code to maximize chrome browser
        driver.manage().window().maximize();

        String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
        driver.get(baseURL);

        //code to click on button using contains()
        driver.findElement(By.xpath("//*[contains(@type,’sub’)]")).click();

        //Close chrome driver.
        driver.close();
    }
}

Let us consider one more example of contains() where we ill click on confirm button using Xpath and contains() method.

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RelativeXpath {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        //code to maximize chrome browser
        driver.manage().window().maximize();

        String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
        driver.get(baseURL);

        //code to click on button using contains()
        driver.findElement(By.xpath("//*[contains(@value,’Confirm’)]")).click();

        //Close chrome driver.
        driver.close();
    }
}

3) Using OR & AND

In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the element.

In the below XPath expression, it identifies the elements whose single or both conditions are true.

DOM :- <input id="alertbtn" class="btn-style" value="Alert" onclick="displayAlert()" type="submit">

Xpath = //*[@id=’alertbtn’ or @value=’Alert’]

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RelativeXpath {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        //code to maximize chrome browser
        driver.manage().window().maximize();

        String baseURL = "https://rahulshettyacademy.com/AutomationPractice/";
        driver.get(baseURL);

        //code to click on button using contains()
        driver.findElement(By.xpath("//*[@id='alertbtn' or @value='Alert']")).click();

        //Close chrome driver.
        driver.close();
    }
}

4) Xpath starts-with

XPath starts-with() is a function used for finding the web element whose attribute value gets changed on refresh or by other dynamic operations on the webpage. In this method, the starting text of the attribute is matched to find the element whose attribute value changes dynamically. You can also find elements whose attribute value is static (not changes).

For example -: Suppose the ID of element changes dynamically like:

Id= "submit123"

Id= "submit456"

Id= "submit789"

and so on but the initial text is same. In this case, we use Start-with expression.

Xpath = //li[starts-with(@class,'gf')]

Using this we can get the count of elements with value of class that starts-with ‘gf’.

5) Xpath Text() function

The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.