Xpath in Selenium with All Tactics and Examples [2021 Guide]

XPath in Selenium tactics will help you how to write dynamic XPath 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. Let’s start to learn all tricks in this XPath tutorial. 

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!

How to Write Dynamic XPath in Selenium Projects for Web Elements

In our test automation projects, 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 dynamic XPath locators. These locators must be capable to locate complex and dynamically changing web elements. In the below sections, I will share with you 15 Tactics to Write Effective XPath Locators.

XPath Selenium Locators Strategies

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 = //img[@alt=’Onur Baskirt‘]

xpath in selenium

You can also use class and src attributes to locate an element with XPath as shown above but always check that there is only one element has been found!

Absolute XPath and Relative XPath in Selenium

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 in Selenium

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

Example: /html[1]/body[1]/div[2]/div[2]/main[1]/div[1]/section[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/h1[1]/strong[1]/span[1]

absolute xpath

Relative XPath in Selenium

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

Example://span[text()=’About Software Test Academy’]

relative xpath

In the above screenshot, SelectorsHub add-on finds a bit different result like: //span[normalize-space()=’About Software Test Academy’] but I used also my tactic which is finding Xpath with text: //span[text()=’About Software Test Academy’] 

In the next section, you will also learn how to find an element with text by XPath in Selenium.

We can also use trailing “//” to continue our XPath search. I will show this in the same example. As you see in the below screenshot I started with “//div”, then I bypassed h1 and strong tags, and continue to my search with the second “//” and then find the element in the span tag. Finally, the statement is finalized as shown below.

Example: //div//span[text()=’About Software Test Academy’]

relative xpath with selectors hub

By the way, I used the SelectorsHub add-on but also you can use ChroPath or Ranorex Selocity as well.

Writing Smart XPaths for Complex and Dynamic Elements

Tag – Attribute – Value Trio

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

Example = //img[@alt=’Onur Baskirt‘]

xpath in selenium

Examples:

//input[@type='send text']

//label[@id='clkBtn']

//input[@value='SEND']

//*[@class='swtestacademy'] --> "*" means, search "swtestacademy" class for all tags.

//a[@href='http://www.swtestacademy.com/']

//img[@src='cdn.medianova.com/images/img_59c4334feaa6d.png']

Contains XPath in Selenium

It is a 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: //img[contains(@alt,’Baskirt’)]

xpath contains

Examples:

//*[contains(@name,'btnClk')] --> It searches "btnClk" for all name attributes in the DOM.

//*[contains(text(),'here')] --> It searches the text "here" in the DOM.

//*[contains(@href,'swtestacademy.com')] --> It searches "swtestacademy.com" link in the DOM.

Starts-with Xpath Examples

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: //img[starts-with(@alt,’Onur Ba’)]

xpath starts-with

Chained Declarations XPath in Selenium

We can chain multiple relative XPath declarations with “//” double slash to find an element location as shown below. We chained “//div” with “//span[text()=’About Software Test Academy’]’ in the below example.

Example: //div//span[text()=’About Software Test Academy’]

relative xpath with selectors hub

Operator “orin Xpath Selenium

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

A B Result
False False No Element
True False Returns A
False True Returns B
True True Returns Both

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

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

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

xpath or example

Operator “and” in Xpath Selenium

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

A B Result
False False No Element
True False No Element
False True No Element
True True Returns Both

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

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

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

xpath and example

How to find XPath by Text 

We can find an element with its exact text.

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

Example://span[text()=’About Software Test Academy’]

relative xpath

Ancestor Xpath Examples

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

1- First, it finds the element whose XPath is //section[@id=’content’]

2- Then, starts to find all div elements in the node where the above XPath belongs to.

Example: //section[@id=’content’]//ancestor::div

ancestor selector

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

//section[@id=’content’]//ancestor::div[1] – Returns 53 nodes
//section[@id=’content’]//ancestor::div[2]- Returns 33 nodes
//section[@id=’content’]//ancestor::div[3] – Returns 24 nodes
//section[@id=’content’]//ancestor::div[4]- Returns 19 nodes

this goes like this. I think you got the idea if not, please write a comment and I will clarify your questions.

Following Xpath Selenium Examples

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

1- First, it finds the this XPath with class attribute: //div[@class=’fusion-sliding-bar-wrapper’]

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

Example//div[@class=’fusion-sliding-bar-wrapper’]//following::section

following example in locators

Child XPath in Selenium Examples

Selects all children elements of the current node.

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

child example in webdriver

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

 find element selenium section

Preceding XPath Examples

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

Example: //div[@id=’wrapper’]/div[@class=’fusion-sliding-bar-wrapper’]//preceding::li

preceding example in selenium

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

Following-sibling XPath Examples

Select the following siblings of the context node.

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

Following-sibling example

Descendant XPath Examples

Identifies and returns all the element descendants to the 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 in selenium

Parent XPath Examples

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

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

xpath parent example

Locate an Element inside Array of Elements

On the Trivago website, let’s search the “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 the 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

If you have any questions or any queries please write a comment. I will try to do my best to reply.

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

Selenium CSS Selector Complete Reference – All Tactics Explained!

I also suggest saving and always use the below reference.

XPath, CSS, DOM and Selenium: The Rosetta Stone

Thanks for reading,
Onur

46 thoughts on “Xpath in Selenium with All Tactics and Examples [2021 Guide]”

  1. 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.

    Reply
  2. 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)

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

    Reply
  4. Hi Onur

    It is really a very nice explanation of XPath with different real time examples.

    Thanks for all your efforts for preparing and sharing the concepts with examples.:)

    Best Regards,
    Sudhakara

    Reply
  5. Thanks for the clear examples, I have been an automation engineer for 1 year+ and as I have a lot of project examples I always reverse engineer the xpaths.

    Now I started a new project from scratch and found this, its a good damn time to learn how to create an xpaths for everything.

    I’m doing xpath angular apps with selenium and with this I’m able to create them.

    Thanks, keep the good work.

    Reply
  6. This such a great tutorial which contains most combinations with examples. Haven’t seen such detailed explanations anywhere. Thank you for creating this. It would be great if you can add any links for practicing / demo links above as well.

    Reply

Leave a Comment

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