How do I find an element in Selenium?
In Selenium, you locate elements with driver.find_element(By.X, "value") for the first match or driver.find_elements(By.X, "value") for all matches. find_element returns a single WebElement and raises NoSuchElementException if nothing matches. find_elements returns a list and gives you an empty list when nothing matches.
from selenium.webdriver.common.by import By
login = driver.find_element(By.ID, "login")
rows = driver.find_elements(By.CSS_SELECTOR, "table.results tr")find_element vs find_elements
find_element returns the first matching WebElement and throws NoSuchElementException when nothing matches, so it fails fast on a missing element. find_elements returns List[WebElement] and returns an empty list on no match, which is the form to use when you want a presence check or need to iterate.
Locator strategies
| Locator | By constant | Use case |
|---|---|---|
| ID | By.ID | Unique element, fastest match |
| Name | By.NAME | Form inputs with a name attribute |
| Class Name | By.CLASS_NAME | Single class, no compound selectors |
| Tag Name | By.TAG_NAME | All elements of one HTML tag |
| Link Text | By.LINK_TEXT | Anchor by exact visible text |
| Partial Link Text | By.PARTIAL_LINK_TEXT | Anchor by substring of visible text |
| CSS Selector | By.CSS_SELECTOR | Flexible, faster than XPath |
| XPath | By.XPATH | Axis navigation, text matching, dynamic DOM |
Related articles
All articles →Web Scraping with XPath in Selenium
Using XPath in Selenium for scraping helps to parse dynamic elements and to find element at any level of DOM structure.
How to Select Elements By Text in XPath?
Discover basic and advanced XPath techniques for selecting web elements by text, including contains(), text(), regular expressions, and more.
CSS Selectors Cheat Sheet: BS4, Scrapy, Selenium
CSS selectors from basic to :has() and :is(), with Python code for scraping and automation. Includes a library support table and resilient selector patterns.
Move Selenium off your own servers
HasData renders pages, rotates proxies, and retries blocked fetches through an API.