Tuesday, 8 October 2013

Selenium Webdriver : Multiple Locators for a Single Element

We all have had dealings with Selenium locators and many times we face with issues with flaky scripts due to flaky locators. The flakiness of the scripts is directly dependent upon the Application Under Test (AUT) .

There might be some situations where one locator might work for an element and the other does not.The natural way that comes to our mind is to use a simple if-else construct and then choose the one that works. This will definitely work, but it's not an elegant solution.

Selenium webdriver has in-built methods to handle this situation and it works for CSS and XPath locator strategy.

XPath

Suppose we have an element with an id = 'login-button' and a name='login-homepage' and lets assume they come under the same div.The way we would write locators using Xpath are as follows.

Using ID : //div[@id='login-button']

Using Name: //div[@name='login-homepage']

Combining both : //div[@id='login-button' or @name='login-homepage']

Ok. It wasn't that hard.Now how it will work is that we have the parent element as the same.But we are not dependent on the locator of the parent Div , but we take the fact that Id , Name are unique for the same web element and work on that.

CSS

CSS also has provisions to combine two locators. Let us assume we have an image with the following HTML

<img src="images/selenium-ide-logo.png" class="icon" alt="Selenium IDE Logo" style="background-color: transparent;">

Using Class : img[class='icon']

Using alt     : img[alt='Selenium IDE Logo']

Combining both : img[class='icon'],img[alt='Selenium IDE Logo']

We can verify the functionality by purposely giving the first locator wrongly,then see whether the second locator works correctly or not and vice versa.

In this way we can combine many locators into one single place in our code such as

String Image_In_Home_Page_Locator = "img[class='icon'],img[alt='Selenium IDE Logo']";

This looks a lot more neater than using if-else conditions.


No comments:

Post a Comment