We have seen eight types of locators in Selenium Webdriver. Now we may confuse which locators we should use. It is frequently asked interview question as well. So, we will learn the orders we should use locators.
Selenium web driver takes time to find web element which is more or less based on type of locator we used. If we use slow locators, it will increase test execution time as well. So, we must use correct and faster locators.
“Name” locator comes after ID. If any web element has not ID attribute, we can use name attribute if available. Even Page Object Model(POM) has advantages when We use name locators. But it may not identify web element uniquely has multiple web elements can share same name. We can ask developers to provide either ID or Name for every web element to faster test script execution.
Locators like ClassName, TagName, LinkText and PartialLinkText are mostly used based on situation. ClassName and TagName can be used to locate a list of web elements while LinkText and PartialLinkText can be used for anchor tag web elements.
“CSS Selector” is best option if web element has no ID and name. It is faster. It also improves the performance. It is very compatible across browsers. It is very useful when we want to test our application on multiple browsers because CSS engine are consistent in all browsers. CSS is best for IE as XPath does not work in IE always. But writing CSS is not simpler than XPath however it is more readable than XPath.
We should use XPath as a last resort to locate a web element. It is slowest among all locators. But it provides you reliable ways to locate web elements. XPath engines are different in each browser, hence make them inconsistent across browsers. That means if you write XPath for your application in Chrome browser, it may not work on IE.
Difference between XPath and CSS:
- CSS is faster than XPath.
- CSS is more consistent across browsers than XPath. CSS is useful for cross browser testing.
- CSS is more readable than XPath.
- CSS can only traverse down the DOM while XPath can traverse DOM up and down.
- CSS improves the performance because it is faster.
- CSS is much better for IE than XPath.
- CSS has deprecated contains method while XPath provides which is very useful in locating web elements.
- CSS is complex and difficult to write compare to XPath.
So, we can define order as below:
ID, Name, CSS , XPath.
That’s it. I hope you should be clear which locators should be used. Now you can give answer of interview question as well. If you have any doubt, please comment or send out an email through contact page.
If you like my posts, please like, comment and share. Feedback and suggestions are always welcomed.