How to Find Element in Selenium Python: Syntax and Examples
In Selenium Python, you find elements using
driver.find_element() or driver.find_elements() with locators like By.ID, By.NAME, or By.XPATH. These methods return a single element or a list of elements matching the locator.Syntax
Use driver.find_element(By.LOCATOR_TYPE, 'locator_value') to find a single element. Use driver.find_elements(By.LOCATOR_TYPE, 'locator_value') to find multiple elements.
By.LOCATOR_TYPE can be ID, NAME, CLASS_NAME, TAG_NAME, CSS_SELECTOR, or XPATH.
python
from selenium import webdriver from selenium.webdriver.common.by import By # Initialize the driver (example with Chrome) driver = webdriver.Chrome() # Find a single element by ID element = driver.find_element(By.ID, 'element_id') # Find multiple elements by class name elements = driver.find_elements(By.CLASS_NAME, 'class_name')
Example
This example opens a webpage and finds the search input box by its name attribute, then prints its tag name.
python
from selenium import webdriver from selenium.webdriver.common.by import By # Setup Chrome driver with webdriver.Chrome() as driver: driver.get('https://www.google.com') # Find the search input box by name search_box = driver.find_element(By.NAME, 'q') # Print the tag name of the element print(search_box.tag_name)
Output
input
Common Pitfalls
- Using deprecated methods like
find_element_by_idinstead offind_element(By.ID, ...). - Not importing
Byfromselenium.webdriver.common.by. - Trying to find elements before the page loads fully, causing
NoSuchElementException. - Using incorrect locator values or types that do not match the HTML.
python
from selenium import webdriver from selenium.webdriver.common.by import By # Wrong (deprecated) way - avoid this # element = driver.find_element_by_id('element_id') # Right way # element = driver.find_element(By.ID, 'element_id')
Quick Reference
| Locator Type | Description | Example Usage |
|---|---|---|
| By.ID | Find element by ID attribute | driver.find_element(By.ID, 'id_value') |
| By.NAME | Find element by name attribute | driver.find_element(By.NAME, 'name_value') |
| By.CLASS_NAME | Find element by class attribute | driver.find_element(By.CLASS_NAME, 'class_value') |
| By.TAG_NAME | Find element by tag name | driver.find_element(By.TAG_NAME, 'tagname') |
| By.CSS_SELECTOR | Find element by CSS selector | driver.find_element(By.CSS_SELECTOR, 'css_selector') |
| By.XPATH | Find element by XPath expression | driver.find_element(By.XPATH, '//tag[@attr="value"]') |
Key Takeaways
Always use driver.find_element(By.LOCATOR_TYPE, 'value') for finding elements in Selenium Python.
Import By from selenium.webdriver.common.by to use locator strategies.
Use find_elements to get multiple elements as a list.
Avoid deprecated find_element_by_* methods; they are removed in recent Selenium versions.
Ensure the page is fully loaded before searching for elements to avoid errors.