Selenium with Javascript – Relative XPath Part 2

Selenium with Javascript – Relative XPath Part 2

We had discussed about different type of Relative XPath in out last session, where we were writing xpath for a particular element based on the attribute and tag of the Element.

So, we had seen different types of Relative XPath so that we can get a unique XPath for an Element which helps in selecting the exact element during the execution of Automation Test Cases.

Now, if suppose, we face below problems

  1. Element doesn’t have any attribute
  2. We are not able to find a unique XPath using the attributes of the Element

then what should we do, Should we go for Absolute XPath, and the answer is a Big No.

So, In this case, we need to find the unique XPath for some near by Element of the Target Element for which we want to find Relative XPath. Once we get a Unique XPath of the near by Element, Then We can find the unique XPath of the Target Element as well.

So, Let’s see it now. Let’s go to our demo ecommerce website and try to find XPath for the products displayed in the Home Page.

Let’s focus on the first Product and try to get the XPath for the image of that Product.

//a[@class='woocommerce-LoopProduct-link woocommerce-loop-product__link']/img - This is not a unique XPath and is going to point out many Elements

//div[@class='astra-shop-thumbnail-wrap']/a/img - This is not a unique XPath and is going to point out many Elements

//ul[@class='products columns-4']/li[1]/div[1]/a[1]/img - This is a unique XPath and is going to point out only the Target Element.

Let’s go to the PDP of our demo ecommerce website, and try to find unique XPath of an Element using the attribute of some near by element. If we go to Description tab, then we find that there are qualities of the Product are displayed, Let’s try to find out the XPath of any one Quality

//li[@class='detail-list'] - This is not a unique XPath and is going to point out many Elements

//ul[@class='prod-list']/li[3] - This is a unique XPath and is going to point out only the Target Element.

Leave a Comment