How to Write Effective XPath Selenium Selectors – All Tactics Explained

XPath Selenium tactics will help you to write effective selenium find by statements especially for locating dynamic web elements in selenium webdriver projects. Generally, test automation engineers struggle to write dynamic XPath at the beginning of their test automation journeys. To address this pain, I prepared this tutorial for writing effective XPath in Selenium.

I shared all my tactics such as XPath contains text, sibling, ancestor, childpreceding, descendant, parent, and so on. I hope this article will help you to write smart and non-brittle selenium find by statements in your projects. Let’s start!

Dynamic Web Elements

In our test automation codes, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not find any of them in the DOM and also sometimes locators of some elements change dynamically in the DOM. In these kinds of situations, we need to use smart locators. These locators must be capable to locate complex and dynamically changing web elements. In below sections, I will share with you 15 tactics to write effective XPath locators.

XPath Selenium Selectors

We can find the location of any element on a web page using XML path expressions. The basic syntax for XPath is shown below:

Syntax = //tagname[@attribute=’Value‘]

Example = //input[@id=’user-message‘]

xpath-selenium

You can also use class, name, link text, and the other attributes to locate an element with XPath as shown above.

Absolute and Relative XPath

Generally, in some test automation engineer interviews, I asked the difference between absolute and relative XPath. Actually, it is the answer is very easy.

Absolute XPath

  • It is a direct way to locate an element.
  • It is very brittle.
  • Starts with single slash “/” that means starting to search from the root.

Example: /html/body/div[2]/div/div[2]/div[1]/div[2]/form/div/input

xpath in selenium

Relative XPath

  • Starts from the middle of the HTML DOM.
  • Starts with a double slash “//” that means it can start to search anywhere in the DOM structure.
  • Shorter than Absolute XPath.
  • Less fragile.

Example: //div[@class=’form-group’]//input[@id=’user-message’]

dynamic xpath

Example: //*[@class=’panel-body’]//li[contains(text(),’entered in input field’)]

xpath contains

Writing Smart XPaths for Complex and Dynamic Elements

Tag – Attribute – Value Trio

Syntax: //tag[@attribute=’value‘]

Example: //input[@id, ‘user-message’]

xpath in selenium

Examples:

Contains

It is very handy XPath Selenium locator and sometimes it saves the life of a test automation engineer. When an attribute of an element is dynamic, then you can use contains() for the constant part of the web element but also you can use contains() in any condition when you need.

Syntax: //tag[contains(@attribute, ‘value‘)]

Example: //input[contains(@id, ‘er-messa’)]

xpath text contains

Examples:

Starts-with

This method checks the starting text of an attribute. It is very handy to use when the attribute value changes dynamically but also you can use this method for non-changing attribute values.

Syntax: //tag[starts-with(@attribute, ‘value‘)]

Example: //input[starts-with(@id, ‘user’)]

xpath selenium java

Chained Declarations

We can chain multiple relative XPath declarations with “//” double slash to find an element location as shown below.

Example: //div[@class=’form-group’]//input[@id=’user-message’]

dynamic xpath in selenium webdriver

Operator “or”

In this method, we use two interrogation conditions such as A and B and return a result-set as shown below:

ABResult
FalseFalseNo Element
TrueFalseReturns A
FalseTrueReturns B
TrueTrueReturns Both

“or” is case-sensitive, you should not use capital “OR”.

Syntax: //tag[XPath Statement-1 or XPath Statement-2]

Example: //*[@id=’user-message’ or @class=’form-control’]

selenium find element by xpath

Operator “and” 

In this method, we use two interrogation conditions such as A and B and return a result-set as shown below:

ABResult
FalseFalseNo Element
TrueFalseNo Element
FalseTrueNo Element
TrueTrueReturns Both

“and” is case-sensitive, you should not use capital “AND”.

Syntax: //tag[XPath Statement-1 and XPath Statement-2]

Example: //*[@id=’user-message’ and @class=’form-control’]

how to write xpath in selenium

Text

We can find an element with its exact text.

Syntax: //tag[text()=’text value‘]

Example: .//label[text()=’Enter message’]

selenium by xpath

Ancestor

It finds the element before the ancestor statement and set it as a top node and then starts to find the elements in that node. In below example,

1- First, it finds the class which id is “container-fluid”

2- Then, starts to find div elements in that node.

Example: //*[@class=’container-fluid’]//ancestor::div

selenium xpath locator

You can select specific div groups by changing div depths as shown below.

.//*[@class=’container-fluid’]//ancestor::div[1] – Returns 13 nodes
.//*[@class=’container-fluid’]//ancestor::div[2] – Returns 7 nodes
.//*[@class=’container-fluid’]//ancestor::div[3] – Returns 5 nodes
.//*[@class=’container-fluid’]//ancestor::div[4] – Returns 3 nodes
.//*[@class=’container-fluid’]//ancestor::div[5] – Returns 1 node

Following

Starts to locate elements after the given parent node. It finds the element before the following statement and set as the top node and then starts to find all elements after that node. In below example,

1- First, it finds the form which id is “gettotal”

2- Then, starts to find all input elements after that node.

Example.//form[@id=’gettotal’]//following::input 

selenium find by xpath

Child

Selects all children elements of the current node.

Example: //nav[@class=’fusion-main-menu’]//ul[@id=’menu-main’]/child::li

 

xpath child

You can also select the required “li” element by using li[1], li[2], li[3], etc. syntax as shown below.

xpath selenium examples

Preceding

Select all nodes that come before the current node. I give an example on swtestacademy. We will find all “li” elements in the homepage. First, we will locate the bottom element, then use preceding with “li” to find all “li” elements as shown below.

Example//img[contains(@src,’cs.mailmunch.co’)]//preceding::li

Also, you can use [1], [2], etc. to select a specific element in the preceding element list.

Following-sibling

Select the following siblings of the context node.

Example: //*[@class=’col-md-6 text-left’]/child::div[2]//*[@class=’panel-body’]//following-sibling::li

xpath syntax selenium

Descendant

Identifies and returns all the element descendants to current element which means traverse down under the current element’s node. Below, the XPath returns all “li” elements under the “menu-main”.

Example//nav[@class=’fusion-main-menu’]//*[@id=’menu-main’]//descendant::li

descendant

Parent

Returns the parent of the current node as shown in the below example.

Example: .//*[@id=’get-input’]/button//parent::form

parent

Locate an Element inside Array of Elements

In Trivago website, lets search “Antalya” keyword. Then, find the first Odamax hotel with XPath.

First, we can find all Odamax hotels by using its text with below XPath:

//span[contains(text(),’odamax’)]

contains text

Above XPath returns many Odamax hotel’s, we can select the first one with below XPath expression:

(//span[contains(text(),’odamax’)])[1]

contains text in selenium

You can also continue to search and find the related hotel’s price element with below XPath:

(//span[contains(text(),’odamax’)])[1]/following-sibling::strong[@class=’deals__price’]

element find by

Also, you can learn how to write effective Selenium CSS locators in below article.

Selenium CSS Selector Complete Reference – All Tactics Explained!

I also suggest to save and always use the below reference.

https://www.red-gate.com/simple-talk/dotnet/net-framework/xpath-css-dom-and-selenium-the-rosetta-stone/ 

See you!
Onur

By |2018-11-27T14:36:40+00:00November 20th, 2018|Selenium Tutorials|22 Comments

About the Author:

Onur Baskirt is a senior IT professional with 10+ years of experience. He worked at Bahçesehir University, ST Microelectronics, Huawei and Ericsson as a research assistant, design verification engineer, and software test leader. Also, he worked as software test leader and software operations manager at Turkey's biggest technology retailer, Teknosa. After Teknosa, he worked as Head of Software Testing and Manager of two Development Teams at Kariyer.net. Now, he is working as a Senior Technical Consultant at Emirates Airlines in Dubai. His current research areas are technical software testing, programming, and computer science. Formerly, he has several research works and papers on digital chip design & verification. His hobbies are sport, dancing, traveling, and nutrition. You can find detailed information about him on his linked-in page.

22 Comments

  1. Kelvin September 28, 2017 at 6:53 pm - Reply

    This is by far the best tutorial on using xpath. It clearly explains the structure of an xpath expression; it then describes the variety of usage, clearly and with great graphics.
    Great work and thanks.
    Kgething.

    • Onur Baskirt September 28, 2017 at 10:14 pm - Reply

      You are welcome Kelvin. I am glad that you liked the article. 🙂

  2. Aleksandar October 3, 2017 at 11:27 am - Reply

    Very clear and easily digestible tutorial.
    Thank you.

  3. […] How to Write Smart XPath Locators […]

  4. Neo January 18, 2018 at 12:53 am - Reply

    I agree. By far the best xpath tut I’ve seen.
    I kind of panicked when I couldn’t find my bookmark anymore (turned out it was on another computer XD)

  5. James April 19, 2018 at 6:45 pm - Reply

    As others have commented, this is a great xpath tutorial. Thank you 🙂

    • Onur Baskirt April 20, 2018 at 12:59 am - Reply

      Thanks for your kind comment. 🙂 That makes me so happy. I am glad that it helps.

  6. Marko Kelovesi May 15, 2018 at 8:05 am - Reply

    I’ve done Robot Framework tests with xpath now about 6 months. Now I learned much more after reading this tutorial. Thank a lot 🙂

  7. srikanth July 20, 2018 at 2:17 pm - Reply

    superb tutorial keep updating about all the concepts

  8. Ram August 6, 2018 at 12:38 pm - Reply

    Fantastic effort to put this up for everyone to use. Thanks a lot

    • Onur Baskirt August 6, 2018 at 1:09 pm - Reply

      Welcome Ram 🙂 Your comment makes my day. Thank you so much.

  9. Andrea August 13, 2018 at 6:57 pm - Reply

    Hi Onur, please do you think you could write a tutorial that explains the difference between dot and text? I found this post but to be honest I’m more confused now than before reading it. Link: https://stackoverflow.com/questions/38240763/xpath-difference-between-dot-and-text
    thanks

    • Onur Baskirt August 14, 2018 at 11:05 am - Reply

      Hi Andrea, I did not use that but I will also check and try to add an section about this. Thank you for pointing out this topic.

      • Andrea August 14, 2018 at 5:41 pm - Reply

        Thanks for the answer Onur. I loved your tutorial and I hope to see more coming !

  10. Luke Chang August 30, 2018 at 12:19 pm - Reply

    Awesome!
    I appreciate this very much.

  11. katt November 19, 2018 at 12:55 am - Reply

    Excellent effort,very helpful thanks for sharing.

    • Onur Baskirt November 19, 2018 at 1:11 am - Reply

      Thank you so much Katt. I am so happy to hear this lovely comment.

Leave A Comment

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