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