How to Find Element by ID in Selenium: Simple Guide
In Selenium, you find an element by its ID using
driver.find_element(By.ID, "element_id"). This method locates the first element with the specified ID on the web page.Syntax
The syntax to find an element by ID in Selenium is:
driver: Your WebDriver instance controlling the browser.find_element: Method to locate a single element.By.ID: Locator strategy specifying to find by ID attribute."element_id": The exact ID value of the HTML element you want to find.
python
from selenium import webdriver from selenium.webdriver.common.by import By # Initialize WebDriver (example with Chrome) driver = webdriver.Chrome() # Find element by ID element = driver.find_element(By.ID, "element_id")
Example
This example opens a webpage and finds a checkbox by its ID, then clicks it.
python
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup WebDriver options = webdriver.ChromeOptions() options.add_argument('--headless') # Run browser in headless mode driver = webdriver.Chrome(options=options) try: # Open example page driver.get("https://www.w3schools.com/howto/howto_css_custom_checkbox.asp") # Find checkbox by ID checkbox = driver.find_element(By.ID, "myCheck") # Check if checkbox is selected print("Initially selected:", checkbox.is_selected()) # Click the checkbox checkbox.click() # Verify checkbox is now selected print("After click selected:", checkbox.is_selected()) finally: driver.quit()
Output
Initially selected: False
After click selected: True
Common Pitfalls
Common mistakes when finding elements by ID include:
- Using the wrong locator method like
By.NAMEinstead ofBy.ID. - Typos in the ID string causing no element found errors.
- Trying to find elements before the page or element has fully loaded.
- Using
find_elementwhen multiple elements share the same ID (which is invalid HTML but can happen).
Always ensure the ID is unique and the page is ready before locating elements.
python
from selenium.webdriver.common.by import By # Wrong way: Using NAME instead of ID # element = driver.find_element(By.NAME, "element_id") # This will fail if element_id is an ID, not a name # Right way: element = driver.find_element(By.ID, "element_id")
Quick Reference
Summary tips for finding elements by ID in Selenium:
- Use
By.IDwithfind_elementfor single elements. - Ensure the ID is unique on the page.
- Wait for the page or element to load before searching.
- Use explicit waits for dynamic content.
Key Takeaways
Use driver.find_element(By.ID, "element_id") to find elements by ID in Selenium.
Ensure the ID string matches exactly and is unique on the page.
Wait for the page or element to load before locating elements to avoid errors.
Avoid confusing locator strategies like By.NAME when you mean By.ID.
Use explicit waits for elements that load dynamically.