DEV Community

Tony Colston
Tony Colston

Posted on

what is a locator in Selenium (and Python)

In order to interact with a web page in Selenium you have to locate the element. As a human you do this without much thought. In Selenium it requires more thought (sadly).

There are lots of ways to find elements on a page. The most specific way is by id. Meaning there is an element on a page and it has a unique id on it. If you looked at the HTML source a unique id would look like this:

<button id="mybutton">click me</button>
Enter fullscreen mode Exit fullscreen mode

When you have a button that has an id on it then you can locate it in Python like this

e = driver.find_element_by_id("mybutton")
Enter fullscreen mode Exit fullscreen mode

Another way to do the exact same thing as above but the code is slightly different.

from selenium.webdriver.common.by import By # note 1
e = driver.find_element(By.ID,"mybutton")
Enter fullscreen mode Exit fullscreen mode

Note 1 - you need another import for this code to work.

If you want to use an XPath locator the code will look like this

driver.find_element(By.XPATH, '//button[text()="click me"]')
Enter fullscreen mode Exit fullscreen mode

There is also a way to find multiple elements that match the same locator by using the find_elements method instead of find_element.

See here for lots more information and all of the other locator types: https://selenium-python.readthedocs.io/locating-elements.html

Top comments (0)