How to Write Smart XPath Locators


Hi all, in this tutorial, I will describe you how to write smart and non-brittle XPath locators. When we write our test scripts, 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 we need to use smart locators for dynamic contents. Thus, in these kinds of situations, we should use smart and non-fragile locators. These locators are capable to find complex and dynamically changing web elements.

XPath Locators

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‘]

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

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’]

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

Writing Smart XPaths for Complex and Dynamic Elements

Reference Demo Site: http://www.seleniumeasy.com/test/basic-first-form-demo.html

1) Writing XPath with Tag & Attribute & Value Trio

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

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

Examples:
Xpath = //input[@type=’send text’]
Xpath = //label[@id=’clkBtn’]
Xpath = //input[@value=’SEND’]
Xpath = //*[@class=’swtestacademy’]
        –> “*” means, search “swtestacademy” class for all tags.

Xpath = //a[@href=’http://www.swtestacademy.com/’]
Xpath = //img[@src=’cdn.medianova.com/images/img_59c4334feaa6d.png’]

2) Writing XPath with contains()

It is very handy XPath 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’)]

Examples:
Xpath = //*[contains(@name,’btnClk’)]
–> It interrogates “btnClk” for all name attributes in the DOM.

Xpath = //*[contains(text(),’here’)]
–> It interrogates the text “here” in the DOM.

Xpath = //*[contains(@href,’swtestacademy.com’)]
–> It interrogates “swtestacademy.com” link in the DOM.

3) Writing XPath with 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’)]

4) Writing XPath with Chained XPaths Declerations

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’]

5) Writing XPath with “or” Statement

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’]

6) Writing XPath with “and Statement

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’]

7) Writing XPath with text()

We can find an element with its exact text.

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

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

8) Writing XPath with ancestor

It finds the element before 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

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

9) Writing XPath with 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 

10) Writing XPath with child

Selects all children elements of the current node.

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

 

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

11) Writing XPath with 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 specific element in preceding element list.

12) Writing XPath with 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

13) Writing XPath with 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

14) Writing XPath with Parent

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

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

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

http://www.swtestacademy.com/css-locators/

I also suggest to save and always use below reference.

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

See you!
Onur

javafx

Database Operations in JavaFX

By Onur Baskirt / Apr 1, 2016 / 56 Comments
Before started this section, please check the first article and learn How to Start JAVAFX! http://www.swtestacademy.com/getting-started-with-javafx/ At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an...
selenium

How to Write Smart XPath Locators

By Onur Baskirt / Sep 24, 2017 / 5 Comments
Hi all, in this tutorial, I will describe you how to write smart and non-brittle XPath locators. When we write our test scripts, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not...
selenium

How to Write Effective CSS Locators

By Onur Baskirt / Oct 1, 2017 / 0 Comments
Hi all, in this tutorial, I will describe you how to write effective CSS locators to interrogate web elements for your automation projects. As a rule of thumb, your interrogation strategy should be in below order: First try to use...
rest assured

REST API Testing with Rest Assured

By Onur Baskirt / Mar 8, 2016 / 32 Comments
Outline In this post, I will explain what is API and API testing, what is the difference between SOAP and REST services, and how to test REST APIs with Rest Assured Library. What is API? API stands for Application Programming...
javafx

Getting Started with JavaFX

By Onur Baskirt / Mar 25, 2016 / 0 Comments
When I started to work in my current position, one of my task is to do manual operations for campaign products  every week. After the second week, I thought that I have to automate this task using a GUI based...
selenium

Selenium-1: Quick Start to Automation with Selenium WebDriver & JAVA & JUnit & Maven & IntelliJ

By Onur Baskirt / Sep 8, 2015 / 26 Comments
Outline Selenium Webdriver is the most popular open source web test automation framework across the wide range of browsers and platforms. In this tutorial, you will learn how to do web test automation with Selenium Webdriver and the related tools....
selenium

Selenium-11: Execute JavaScript with JavascriptExecutor

By Onur Baskirt / Jan 27, 2016 / 15 Comments
Outline Sometimes we cannot handle some conditions or problems with Webdriver, web controls don't react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change...
page object model

Page Object Model with C#

By Ege Aksoz / Jun 18, 2017 / 8 Comments
In the previous tutorial, we’ve taken the initial steps and entered the world of automated testing. We also wrote our first automated test. From this point on, since we are not just going to write one test, we need to...
selenium

How to Select a Date From DatePicker Using Selenium

By Onur Baskirt / Aug 13, 2016 / 6 Comments
When you need to automate a airway, hotel, or similar websites you need to deal with Datepickers and some times it is a little bit cumbersome to select a specific date on the Datepicker or calendar.  In this post, I...

Getting Started with RobotFramework on Windows

By Onur Baskirt / Apr 25, 2016 / 12 Comments
What is RobotFramework? RobotFramework is a GENERIC test automation framework for acceptance testing and acceptance test-driven development (ATTD). What it means that you can do web, mobile, desktop and other test automation activities with related test libraries. These libraries can...
By | 2017-10-22T23:42:10+00:00 September 24th, 2017|Selenium, Test Automation|5 Comments

About the Author:

Onur Baskirt
Onur Baskirt is a senior IT professional with 10+ years of experience. He worked at Bahçesehir University, ST Microelectronics, Huawei and Ericsson as 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. Now, he is working as Head of Software Testing and Manager of two Development Teams at Kariyer.net. 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.

5 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
      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 […]

Leave A Comment