Xpath -Types and Examples


In this article, I will explain about what is Xpath, types of xpath, absolute xpath, relative xpath, advantages and disadvantages of both types, how to create absolute and relative xpath. Also I am going to explain few examples of xpath like how to find xpath on form having two buttons, checkbox checked or not, enter value in textbox.

Xpath is a locator used for locating nodes in XML and HTML.

Let's say user wants to search something in google so user needs to type something in search textbox of google page. To perform this activity what we need is the identification of Search textbox of google page. So for doing that Selenium provides different types of Web element locators. Xpath is one of them which identifies web element uniquely in web page. Xpath is nothing but the unique address of that web element in web page.

Xpath is used to target web elements on web page.
When unique id or name is not available in web page then Xpath is used.

There are two types of Xpath.

  1. Absolute Xpath
  2. Relative Xpath

Absolute Xpath

  • Absolute xpath starts from root element (html) and ends with the desire element.

  • It starts with single slash i.e. "/". Single slash instructs Xpath engine to look for element from root i.e. from html. Also single slash means it directly access the immediate parent node. If any node is missed while writing Xpath, then it cannot access the element.

  • Advantage: It identifies the element very fast.
    Disadvantage: In case of slight change in HTML, xpath get change.

  • How to create absolute Xpath?
    Suppose we want to automate the functionality of register link on one mobile recharge website. So to locate element on web page, right click on 'Register' link and select 'Inspect Element' option. Below HTML page will get display.
    xpath

  • Now, to create absolute Xpath for the Register link we need to navigate through all tags from html to the desired link.
    So our Xpath will be "/html/body/div/table/tbody/tr/td/a[4]"

Relative xpath

  • Starts with double forward slash "//".

  • It directly accesses the desired node. If desired node is not directly accessible then it locates the nearest element and creates Xpath from that node.

  • Advantages: As it directly locates the element, changes in web page (addition or removal of web element) does not cause much impact on relative Xpath.
    Disadvantages: It takes more time to identify element using relative way as we are providing partial path and not exact path.

  • How to create Relative Xpath?
    For same link we can write Xpath by Relative method.
    Register link have 'a' tag and have class and href attributes. But we cannot use class attribute as it have same values for other 'a' tag. So by using href attribute below will be the xpath.
    Xpath: //a[@href="http://www.easymobilerecharge.com/signmeup.php"]
Also we can write Xpath by combining both the types.
For example, for register link we can write xpath like "//td/a[4]".
Here, we started with relative xpath by writing '//' and then used absolute xpath to reach that node.

Some examples to write Xpath

  1. If you have given one form which has two buttons, html of form will be as below:
    <html>
    <body>
    <form>
    <button id="a" onclick="alert('Button1 Clicked!')" button="AAA" type="button">Button1</button>
    <button id="b" onclick="alert('Button2 Clicked!')" button="AAA" type="button">Button2</button>
    </form>
    </body>
    </html>


    So write xpath to click on second button.
    Absolute Xpath - /html/body/form/button[2]
    Relative Xpath - //button[@id='b']

  2. If you have check box in your form then by using xpath how you will verify that checkbox is checked or not.
    HTML Code:
    <html>
    <body>
    <form>
    Cricket:
    <input id="chkbox1" class="selected" type="checkbox" Checked>
    <br>
    Football:
    <input id="chkbox2" class="unselected" type="checkbox">
    </form>
    </body>
    </html>


    We will use isSelected() method to check whether checkbox is checked or not. Below is the java code for the same.

    Java Code:

    WebElement element=driver.findElement(By.xpath("//input[@id='chkbox2']"));
    boolean a = element.isSelected();
    System.out.println(a);

    Output: false
    By using Xpath, first it will find the checkbox. Then isSelected() method will verify that element is checked or not and will give result in Boolean format.

  3. And if your isSelected() method is not working then how you will write xpath to identify that checkbox is checked or not.
    Java Code:
    WebElement element=driver.findElement(By.xpath("//input[@id='chkbox1']"));
    System.out.println(element.getAttribute("Checked"));


    In html, to represent any checked checkbox 'Checked' attribute is used. Here, we have used 'getAttribute' method to verify that 'Checked' attribute is available or not. getAttribute method returns the value of specified attribute. If specified attribute is not available then it gives NULL value.
    So, here it will verify that 'Checked' attribute is available or not. If yes then it will print the value otherwise print the NULL.

  4. If your form contains four checkbox then write xpath to identify which checkbox is checked.
    Java code:
    List<WebElement> lst = driver.findElements(By.xpath("html/body/form/input"));
    int listCount = lst.size();
    System.out.println(listCount);

    for(int i=0; i<listCount; i++)
    {
    if(lst.get(i).getAttribute("Checked") != null){
    System.out.println(lst.get(i).getAttribute("id") + " is checked");
    }


    Here, we have used List interface. List interface is a subtype of Collection data structure.
    In Java, Array is used to store multiple object data. But drawback of array is user need to initialize size of array during instantiation. So to overcome that drawback 'Collection' data structure is used. In collection, we can store any type of object without giving size while instantiation.

    As we want to store all the web elements of specified path, we have given List type as WebElement. As per the requirement we can store string Integer or combination of data.
    We have created 'lst' object of List interface and stored all the web elements in it.
    After that we have initialize listCount variable of Integer type which will save the size of list by using size() method of List interface.
    Then by using getAttribute() method we need to verify that checkbox is checked or not.

  5. If in your form you have text boxes which vary in number when you load the page then how you will write value in second last text box always.
    driver.get("Web address");
    List lst= driver.findElements(By.xpath("html/body/form/input"));
    int txtCount=lst.size();
    System.out.println(txtCount);

    for (int i=txtCount; i>=0;i--)
    {
    if (i==(txtCount-1))
    {
    WebElement wb= driver.findElement(By.xpath("html/body/form/input[" + i + "]"));
    wb.sendKeys("Hi");
    }
    else
    {
    System.out.println("In else block");
    }
    }


Attachments

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: