How To Write XPath In Selenium WebDriver With Example?

Most difficult thing in Selenium is finding correct Locators, Here we are going to see how to find xpath in Selenium but before that we are going to see the division of  of object/element  Identification, Locator (xpath, css and other locators ) are divided in three category. these are as follows

1)      Location based Identification

2)      Cell based Identification

3)      Property based identification

Xpath is one example of Cell based Identification and this is further divided in four part

1)      Assess the structure of the application pages and how best to locate a label on the page:  Accessing certain structure of a web page is totally dependent on the type of application that we are using. Since we are taking webpage as the application so obliviously we will deal with HTML to  access the structure of page

Xpath In Selenium WebDriver

Suppose the html for above page is

<Table>
<tbody>
<tr>
<td>
<span>Username</span></td>
<input id=”hfeb” type=”text”

<span>Password</span></td>
<input id=”hjhflds” type=”text”

</tbody>

<table>

From here we can see that page contains table and labels like Username and Password which is mainly present in span tag without any special property so we can track this label username and password by its text so its

Xpath would be

//span[text()=’Username’]

2)      Identify the structural relationship between a label and its associated field: Now we should deal with the relationship with Label and Field and how they are related to each other.

In our case Username and Text field comes in the same row and we are not using any cryptic and dynamic function to handle text field

3)      Construction of Xpath to identify the element that we have to use in our Selenium script: Construction of xpath is also divided in 3 parts

  • Locating the label
  • Using the label to find the parent row element
  • Find the desired child field of the row element

The label can be located with the following XPath statement from

Step 1:

//span[text()=’Username’]

This XPath can then be modified to get to the parent row element. To do this, it is important to note that the row (TR) element is not the direct parent of the Span element. The column element represented by the td tag is the direct parent of the Span element. The tr element is the parent of the td element. Therefore, to get to the tr element, we must travel two levels up the parent hierarchy. This can be done with the following statement:

//span[text()=’Username’]/../..

Adding ‘/..’ moves the reference up one level from the SPAN element (the label) to

the SPAN element’s direct parent. Since the parent row element (TR), we now need to update the statement to get the child textbox of that row, which is represented in the HTML by the input tag. This is done by modifying the previous XPath statement to appear as follows:

//span[text()=’Username’]/../..//input

Since there is only one input element that is a child of the row element, there is no need to use any properties to further we need to go up two levels, we can do this with ‘/../..’. Once we have access to identify the input element.

4)      Using Xpath in appropriate place in script: Since we are now familiar with the xpath of

Username and password like this

driver.findElement(By.xpath(“//span[text()=’Username’]/../..//input”))

Few more work out example to learn xpath

Example 1: /AAA

This xpath says : “Select all root  AAA

<AAA> 
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
     </AAA>

Example 2: /AAA/CCC

This Xpath says : “Select all child CCC of  root AAA”

<AAA>
<BBB/>
          <CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>

Example 3: /AAA/DDD/BBB

This xpath says “Select all BBB which are children of DDD and which is further children of  root AAA”

 

<AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>

Example 4:

//BBB

This xpath says “to select all BBB”

 

<AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>

Example 5:

//DDD/BBB

This  Xpath says “Select all BBB which is the children of DDD

 

<AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>

Example 6:

/AAA/DDD/*

 

This Xpath says “Select all element which are enclosed by /AAA/DDD

 

Example 7: //*

Select all elements in the HTML file

 

Example 8: /AAA/BBB[1]

This xpath says “select first Chil BBB of AAA

 

<AAA>

<BBB>

<BBB>

<BBB>

<BBB>

</AAA>

But to select the last BBB child of AAA

We can write

/AAA/BBB[Last()]

 

Example 9:

 

<AAA>
b1″/>
b2″/>
bbb”/>
<BBB/>
</AAA>

//@id

This xpath says: “Select all Id attribute

 

//BBB[@name]

This xpath says: “select all BBB with attribute “name””

 

bbb”/>

If we want to select all BBB in above html

 

Then xpath will be

//BBB[@*]

If we want to select only one BBB that don’t have any attribute in above html then

//BBB[not(@*)] 

If we want to select some specific BBB with its attributes value then

//BBB[@name=”bbb”]

Then it will select BBB where value of its attribute is bbb

Then in above HTML

bbb”/>

Friends please let me know if I am missing some concept of XPath  and in next post i will cover how xpath can be found out by using firebug along with firepath in selenium

Reference:

http://www.zvon.org/xxl/XPathTutorial/General/examples.html

http://wikipedia.org

 

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

26 Responses

  1. Enrique Izaguirre says:

    Thanks. It is very good.
    I have one that I still cannot make work: I want to click in an href attribute, which is inside an Something like this:
    <span class=" cl1"

    I tried with: //span[@class, ‘cl1’]/a[@href] and tried other combinations, but it doesn’t work.

    Could you help please?

    • use //span[@classs=’cl1′]/a

      if you just want to click on a link then use

      you can use

      driver.findElement(By.linkText(“Text to which you want to click”).click();

      • Hi Dwarika,

        Reg for selenium in webdriver i have created script for login page for my application. After that next screen i want click on ‘some tab’ so for that what i need to write code for that and which xpath i need to use. Please do the needfull.

        Thanks in advance.

        Regards,
        LNarayana

  2. Enrique Izaguirre says:

    oops, the last comment is missing some parts. the problem is that I want to access a reference or link that is an argument inside an “<a" which is inside an "<span

  3. Sivaranjini says:

    Could u pls tel me how to do a case insensitive search using XPath text()

  4. Timo says:

    Hello I am having trouble identifying the following Xpath. I have tried via ID but it doesn’t locate the element.

    Card Number

    driver.findElement(By.xpath(__________)

    Thanks a lot.

  5. autumnator says:

    There’s a lot more to power of XPath not presented here. For example

    //div/following-sibling::span[contains(text(),’some text’)]

    features like following-sibling, preceding-sibling are useful to navigate relative to a node that’s eays to locate. and you can use contains() to match by node text or attribute text when it is partial text match and not absolute text match.

    then there’s

    //div[div[contains(@value,’123′)]]

    which finds a div that contains a descendant div that contains value attribute of ‘123’

    and then there’s

    (//someXpath)[3]

    which will find all matches for “//someXpath” and assuming there is more than 3, will return the 3rd match. so for example

    (//div[@value=’test’][3])[1]

    will find all elements of matches of “//div[@value=’test’][3]” then get the 1st of those.

    • Thank you for drafting such a nice and informative comment post. Actually I was thinking to write the same in my coming post and through this comment I have felt that I should include this on priority basis.

      Once Again thank you for your comment

  6. Ashok says:

    Hi,
    I am new to java. Could you please tell me how to retrieve multiple values in single column. The code getCell(0,row), 0 means column as my understanding and what is row?

    String username = s.getCell(0, row).getContents();
    System.out.println(“Username “+username);
    driver.get(“http://www.gmail.com”);

    Column 1: Column 2:

    Row 1: Yahoo Registration1 Yahoo Registration2

    Row 2: First Name First Name

    Row 3: Last Name Last Name

    Rows ect.. ect…..

  7. Sham says:

    Hi, I have a question regarding Xpath with span and class together.
    Below is the HTML;

    Market Data

    I have tried with below 2 xpaths, its not working, please help

    (By.linkText(“Market Data”)).click();
    (By.xpath(“//li[class[contains(@text,’Market Data’)]]”)).click();

  8. shruthi says:

    Hi can u please explain how to write Xpath for dependent element?

  9. Shweta says:

    Hi,
    I have a question. M having a problem with table which changes values dynamically. I have a table which have 50 rows and 14 columns. 1st column is of states and others are months. 1st row is titles. ie. state|january… like that. but as every time page reloads the state names and months names changes their positions. like if 1st state name currently is Gujarat and 1st month is january, march,february, november….
    now if page reload or refresh gujarat will move from 1st position to some other way in that column and the sequence on months will also changes ie. now may b 1st month will be november,septmber…

    Now my question is i want to get value stored in cell of December month for state Bihar. how to do this using xpath?
    I tried driver.findElement(By.xpath(“//td[contains(text(),’Bihar’)]”)).getText();
    thus atleast I can focus on Bihar word where ever it will be present in htm page bt now how to catch cell value of December month for this state?

  10. thamizhkumaran ayyanar says:

    Hi All,
    Can any pls help me out.
    i am struggling lot will type the card number in payment page
    after i enter the card number in the field,It need to be converted some special character.
    how to handle in this situations.
    Thanks
    Thamizh

  11. Ganesh Devavarapu says:

    Hi,
    HTML of the table content: …

    I need to click on this link. Could you please help on Xpath of this object

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.