Tuesday, 27 May 2014

Selenium xpath powerfull tips

In this post, I will share with you a few useful xpath locator pointing techniques that can come handy in complex situations.

1) When you have a button click that loads either 'Page A' or 'Page B' which you are not certain about.

In the above situation,  you need to identify a unique element from both pages first manually. Then use it with an OR (|) operator.

for eg: 
Page A contains: //input[@name='eventId']
Page B contains: //span[@class='alert']

Now you can use the OR operator to make selenium wait for the following xpath:

waitForElement(By.xpath("//input[@name='eventId'] | //span[@class='alert']");

Notice the OR operator in yellow font.

This is handy when you can make sure that one of the required page is loaded.


2)Not many of us know that xpath is a powerful means to locate elemenst on the screen.

Descendant: Finds desired html node that comes as any degree child of a parent node.
for eg:
//div[contains(@class, 'aboveNav')]/descendant::img[contains(@class, 'logo')]"]

here by using 'descendant' you are actually asking selenium to find 'img' node that is under the 'div' node.

Parent:Find the parent node of the previously invoked node.
for eg:
//a[@name='GRND']/parent::div

Here selenium can actually select the div that is the parent of node 'a'

Sibling: Finds the sibling node of the previously invoked node.
for eg:
//a[@name='GRND']/parent::div/following-sibling::div


4 comments:

  1. I guess in general using Absolute path is better than Relative path? Please correct if am wrong.
    Your blog is very helpful could you please post more articles?

    Test Automation

    ReplyDelete
    Replies
    1. Absolute path mentions all the parent paths of the object where as a relative path only gives connectivity between parent nod and the child nod.

      In my experience, its better to go with relative path as the page model (UI) can change. In such a situation absolute path may not sustain.

      For eg:
      an absolute path: //div[4]/div/div/div/a
      here if a 'div' is removed, then we wont be able to get access to our object identified 'a'.

      Hope I am clear to you. Please do let me know if you think other wise.

      Many will say not to use xpath, but xpath is really powerfull if we know how to use it.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thank you for the explanation

    ReplyDelete