Learning xpath concepts

The very first step in the automation comes up with locating elements in a webpage to perform some operation. If you want to learn Selenium, then you must know different ways to locate an element using XPath.

There are two types of Xpaths -

  1. Absolute XPath
  2. Relative XPath

Absolute Xpath is taken from the root node of the webpage. It is not recommended to use in the automation scripts because web elements keep on changing and your script will require high maintenance if you use absolute XPath. It starts with a single slash. for example -

/input[@name= 'username']
Relative XPath, on the other hand, is a dynamic XPath and can be started with any reference web element or text on the screen. It is the most useful and recommended method to use to locate the web element. It is started with a double slash, for example -

//input[@name=' username']

Let's understand the XPath axes which can come in very handy to deal with complex web elements on a webpage. It defines the relationship of a web element with other web elements.


  • ancestor
  • ancestor-or-self
  • child
  • descendant
  • descendant-or-self
  • following
  • following-sibling
  • namespace
  • parent
  • preceding
  • self
Syntax - Xpath=//*[@id='<id attribute of an Element>']//parent::div

Different functions that can be used while finding an XPath with text -
  • Contains()
  • Starts-with()
  • Text()
  • And/Or
  • Ends-with()
    • Example -//input[@type='checkbox' and starts-with(@name,'favorite')]
Interview question - How would you find the last and second last element in a DOM using XPath if you don't know the number of tags in an parent or let's say they are dynamic?
  • In this case, we would consider inbuilt function for Xpath.
  • //tr[last()]/td[1]
Finding XPath with reference to the parent, for an example -

Parent XPath

Parent XPath

//img[@alt='smiley']/parent::p or //img[@alt='smiley']/..

Ancestor XPath

Now where can we use ancestor? In above example we can also use ancestor in place of parent. Ancestor have a broader range than parent.

//img[@alt='smiley']/ancestor::p or //img[@alt='smiley']//ancestor::div or //img[@alt='smiley']//ancestor::*

That's all we can cover under ancestor and parent. Now let us look at the Siblings concept for XPath.

Sibling XPath



























Let's say we want to extract age of Amanda Madison in above snippet

//td[preceding-sibling::td[text()='Madison']]

We can also use below XPath to find the same element

//td[text()='Madison']/following-sibling::td

Both the above XPaths will find 22.

If we want to use cssSelector property instead of XPath, we should know how to convert XPath into cssSelector. For an example -

XPath - //*[@id='nav-orders']/span[2]
cssSelector = *[id='nav-orders'] span:nth-child(2


Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD