0
0
Selenium-pythonHow-ToBeginner ยท 4 min read

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_id instead of find_element(By.ID, ...).
  • Not importing By from selenium.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 TypeDescriptionExample Usage
By.IDFind element by ID attributedriver.find_element(By.ID, 'id_value')
By.NAMEFind element by name attributedriver.find_element(By.NAME, 'name_value')
By.CLASS_NAMEFind element by class attributedriver.find_element(By.CLASS_NAME, 'class_value')
By.TAG_NAMEFind element by tag namedriver.find_element(By.TAG_NAME, 'tagname')
By.CSS_SELECTORFind element by CSS selectordriver.find_element(By.CSS_SELECTOR, 'css_selector')
By.XPATHFind element by XPath expressiondriver.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.