Andy Tilston Andy Tilston - 2 months ago 22
Java Question

Advise on hierarchy for element locators in selenium webdriver

whilst I am aware of how to search for the different elements on a page in Selenium Webdriver to usr for testing, xpath, id, css etc, I was after some advise as to which hierarchy to use and why? E.g. should we use xpath locators before reverting to searching for the id?

Having an awareness of this will allow me to build my tests in the correct way so that they run as quickly as possible.


As far as I my experience with selenium I think following is best hierarchy :

  1. Id

  2. Name

  3. Linktext

  4. Partial Linktext

  5. Tag Name

  6. class name

  7. Css

  8. xpath

1 - By ID for each and every element is always unique so easy to access for us and fast for web driver.Mostly we should prefer Id as first priority to find element.

2 - If By ID is not Ok then we should look at "Name". But many time it happens that multiple name is there so need to take care for this if same name attribute is multiple times there.

3 - "By linktext" & "By partial linktext" are also great ways to find element if all links in site have unique link text.

4 - If your site or page has group elements like dropdown , checkboxes then you can use attribute "By tagname" to find element.

5 - By "Class name" is rare way to find element because most of website using same class name for multiple items to apply css. But sure you can use it for unique class names.

6 - If you need speed to locate complex elements then kindly use attribute "Css selector" to find element.

7 - Main use of "Xpath" attribute to navigate for xml documents. Still you can use it for web page or site.

Note : Basically selection of element locator depends on your page that which type of things page contains like too many dropdowns , checkboxes, textboxes and a lot more. But my given steps are general which you can follow for any site to find elements and execute program in smooth way.

Hope above will help you a lot.

Other Reference link :