HasData
Back to Q&A

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

LocatorBy constantUse case
IDBy.IDUnique element, fastest match
NameBy.NAMEForm inputs with a name attribute
Class NameBy.CLASS_NAMESingle class, no compound selectors
Tag NameBy.TAG_NAMEAll elements of one HTML tag
Link TextBy.LINK_TEXTAnchor by exact visible text
Partial Link TextBy.PARTIAL_LINK_TEXTAnchor by substring of visible text
CSS SelectorBy.CSS_SELECTORFlexible, faster than XPath
XPathBy.XPATHAxis navigation, text matching, dynamic DOM

Move Selenium off your own servers

HasData renders pages, rotates proxies, and retries blocked fetches through an API.