DEV Community

Tony Colston
Tony Colston

Posted on

1 1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay