Selenium - Locators

By xngo on June 17, 2019

In order for Selenium to control and manipulate each HTML element(e.g. <a>, <input>, <div>, etc) on the website, you have to provide it with a reference to each element. That reference is used by Selenium to identify the element and apply the actions on that element. The term used in Selenium to denote the reference of an element is called locator.

There are different types of locators. For the complete list, see Locators documentation section below. The following are the most commonly used types of locators:

id=id
Refer to the element with the specified @id attribute.
HTML:
<div id="unique_logo_id"></div>
----------------------------------------
Locator:
id=unique_logo_id
name=name
Refer to the element with the specified @name attribute.
HTML:
<input name="first_name" />
----------------------------------------
Locator:
name=first_name
xpath=xpathExpression
Refer to the element with the specified Xpath expression.
HTML:
<table>
    <tbody>
        <tr><td>cell1</td></tr>
        <tr><td id="cell_id_2">cell2</td></tr>
    </tbody>
</table>
----------------------------------------
Locator:
xpath=//table/tbody/tr/td[text()='cell2']
xpath=//*[@id='cell_id_2']
xpath=//td[text()='cell2']
xpath=//td[contains(text(), '2')]
link=textPattern
Refer to a link with the specified text pattern.
HTML:
<a href="page2.html">Next</a>
----------------------------------------
Locator:
link=Next
link=regexp:[nN][eE][xX][tT]
link=regexpi:NEXT

By default, if the type of locator is not explicitly specified, Selenium will assume that it is an @id. If no match is found, then it will assume that it is a @name.

Therefore, given that you provide the locator of the desired element, Selenium will be able to click or type on that element, retrieve text from that element, etc. Most of the functions provided by Selenium use locator. Hence, it is important that you master the locator in order to be able to use Selenium efficiently.

Locators documentation

  • For Python, see https://selenium-python.readthedocs.io/locating-elements.html
  • For Java, see https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/By.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.