Various locators types

Selenium webdriver basically uses 7 locators to find the elements on the web page. The following are the list of locators supported by selenium.
1. ID
2. Name
3. Class Name
4. Tag Name
5. Link Text & Partial Link Text
6. CSS Selector
7. XPath

In Selenium Webdriver, we use findElement() method to locate the elements on the browsers. Inside the findElement method we use By.locatorName() method. Here in this method, we replace lacatorName() section with locator names.

Below are the brief description of the above locators.

1. ID

ID’s are basically unique for each element so it is a common way to locate the elements using ID Locator on browsers. Also, the ID locator is the fastest locator from all other locators.
Syntax: driver.findElement(“ID”))

2. Name

Finding or Locating elements by name is very much similar to locating by ID, here we use the “name=” prefix.
Note: Names values are not unique on the page. If there are multiple elements with the same Name locator then the first element on the page is selected. A test may fail if another element with the same Name locator is present on the web page or added by the developers in the later stages.
Syntax: driver.findElement(“Name”))

3. Class Name

Class Name locator provides the element which matches the values specified in the attribute name “class”.
Syntax: driver.findElement(By.className(“Element Class”))

4. Tag Name

Tag Name locator provides the element which matches the values specified in the Tag Name.
driver.findElement(By.tagName(“HTML Tag Name”))

5. Link Text & Partial Link Text

Link Text and Partial Link Text locators work on the hyperlink that’s why these are called link text locators. If there are multiple elements with the same link text then the first one will be selected.

6. CSS Selector

CSS Selectors are the string patterns used to identify an element based on a combination of HTML tags like id, class, and other attributes. Locating by CSS Selector is more difficult than the previous methods, but it is the most common locating strategy of advanced Selenium users because it can access even those elements that have no ID or name.

CSS Selectors have many formats, few of the most commons are.
1. Tag and ID
2. Tag and class
3. Tag and attribute
4. Tag, class, and attribute
5. Inner text

Following are few mainly used formats of CSS Selectors
Tag and ID

Tag and Class

Tag and Attribute

Tag, Class and Attribute

Inner text
tag:contains(“inner text”)

7. xpath

XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing. XPath produces reliable locators but in performance wise it is slower (especially in IE older versions) compared to CSS Selector.