Different locators in selenium and when to use them

Posted on

While creating automation tests using selenium, we use locators to find elements and perform required operation on them. We use different locators at different time based on the structure of the application layout. In this post we will see what are the different locators and when to use each of them. Following are the locators used in selenium.
  1. Id
  2. Name
  3. Classname
  4. CSS Selector
  5. Tag Name
  6. XPath
  7. Link Text
  8. Partial Link Text

Using Id and Name

Always prefer Id among other locators if it is available. Id requires to be the unique one for that application, hence it is easy to locate. It's not necessary that Id will always be unique. Sometime there will be multiple instance of same Id within same layout. This is due to poor development and you should immediately report the same and get it fixed.

While selecting Id as a locator, you should inspect that if the given Id is not dynamic. Sometimes dynamically generated content can have dynamic Id which will change every time when the content is loaded.
Similarly in the case of Name, but give second priority to name. Again you need to check if the Name is unique. I case of radio button, Name can be same for all the radio button of that group. At such situation you need to tag advantage of other unique locators available.

Class Name

Class name may or may not be unique in a block of html code as the same class name might have been used for multiple web elements. The class names are used to add similar style to a list of items belong to a single category eg. list items, rows, any web elements etc. While performing the selenium automation testing, class name is used with findelements in most of the cases to get list of similar items from the web page.

Tag Name

Tag Name is used when you don't have a unique identifier for the given element and it's tag is the only one in the page. This can also be used with findElements when there are multiple element with same tag name available in the page and you want to iterate through all the elements.

CSS Selector and XPath

CSS Path and XPath are used for selecting elements in complex html blocks. XPath can be static or dynamic and can be relative or absolute. XPath can traverse in both forward and backward direction. CSS Selector can only traverse through forward direction. CSS Selector considered as faster than XPath.

Link Text and Partial Link Text

Link Texts and Partial Link Text are used to select an element with anchor tag. Link Text will work with the full text comparison in a hyperlink. The uniqueness is depending on the unique text of the hyperlink. On the other hand partial link text is used to select the hyperlink matching the part of text in a hyperlink. Here you don't need to have full text comparison.