Mastering XPath for Selenium Test Automation

Mastering XPath or CSS is essential for the Selenium test automation engineers to locate dynamic web elements. It is noted that new Selenium automation engineers do not pay much attention to master location strategies. This leads to failure of test automation efforts when web pages with dynamic contents are automated. Most of the testers rely on extracting the XPaths from Firebug/Firepath like tools. The tools cannot be used directly for dynamic web elements. We will discuss XPath in detail with examples.

XPath for locating Web Elements

I have my own way of introducing  (explaining) XPath to the trainees in my training sessions.

When A=B and B=C. I ask the students what can be derived from these expressions. Immediately they reply with A=C.

Then I give following two statements

  • XPath is used for  locating the elements in XML documents

  • XML and HTML has similar syntax (HTML is an XML file)

Hence XPath can be used for locating elements in HTML pages/web pages.

Why do we need to master many XPath syntaxes

We may not be able to locate the elements directly using their unique attributes as some element do not have unique attributes. Some attributes are dynamically changed.[/box] Hence we may have to locate them differently than the static elements.

  • Locate elements with respective a known element

  • Locate elements with partial fixed attribute values

  • Locate element without attributes or without unique attributes

  • XPath can do bidirectional navigation (Going forward and backward)

  • XPath is one of most flexible and strongest location strategy

Types of XPath

  • Absolute XPath

Absolute XPaths starts with the root of the html pages.

Absolute XPaths are not advisable for most of the time due to following reasons

  1. Absolute XPaths are lengthier and not readable

  2. Absolute XPaths are brittle when minor structural changes are done to the web pages

Absolute XPaths shall be used only when a relative a XPath cannot be constructed. (highly unlikely). Absolute XPaths tends to break as web pages/content is changed. Hence it not recommended to use absolute XPath in Selenium.

Most of the beginners tend use absolute XPaths when they copy them from tools like FireBug. Theses XPaths are tend to break (brittle) most of the time.

Syntax: Absolute XPaths start with  /html

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

  • Relative XPath

Relative XPaths is used for locating an element from a known element. The element of your choice is referred relative to a known element.

Syntax : Relative XPaths are started with two  forward slashes. //

Example : //div[@id=’divUsername’]/input

Absolute XPaths are faster than the relative XPaths


Posted in Selenium.

Leave a Reply

Your email address will not be published. Required fields are marked *