0
0
Selenium Pythontesting~5 mins

Find element by ID in Selenium Python

Choose your learning style9 modes available
Introduction

Finding an element by its ID helps you quickly locate a unique part of a webpage to test or interact with.

You want to click a button with a unique ID.
You need to check the text inside a specific section identified by an ID.
You want to enter text into a form field that has an ID.
You need to verify if an element with a certain ID is visible on the page.
Syntax
Selenium Python
element = driver.find_element(By.ID, "element_id")

Use By.ID to specify you are searching by the element's ID attribute.

The ID should be unique on the page for accurate results.

Examples
Finds the element with ID 'submit-button' to click or check.
Selenium Python
element = driver.find_element(By.ID, "submit-button")
Locates the username input field by its ID to enter text.
Selenium Python
input_field = driver.find_element(By.ID, "username")
Sample Program

This script opens a simple webpage with a button that has an ID 'test-button'. It finds the button by its ID and prints its text.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# Setup Chrome driver options
options = Options()
options.add_argument('--headless')  # Run browser in headless mode

# Setup Chrome driver service (adjust path to chromedriver as needed)
service = Service()
driver = webdriver.Chrome(service=service, options=options)

try:
    # Open a simple test page
    driver.get("data:text/html,<html><body><button id='test-button'>Click me</button></body></html>")

    # Find the button by ID
    button = driver.find_element(By.ID, "test-button")

    # Print the button text
    print(button.text)

finally:
    driver.quit()
OutputSuccess
Important Notes

Always ensure the ID you use is unique on the page to avoid finding the wrong element.

If the element is not found, Selenium will raise a NoSuchElementException.

Use headless mode in tests to run faster without opening a browser window.

Summary

Use find_element(By.ID, "id") to locate elements uniquely by their ID.

IDs are unique, so this method is fast and reliable.

Handle exceptions if the element might not be present.