Selenium Element Finder by ID with Timeout

  • Share this:

Code introduction


This function uses the WebDriverWait and expected_conditions from the selenium library to wait for an element on the page to be loaded by its ID. If a timeout occurs, it prints an error message and returns None.


Technology Stack : selenium, WebDriverWait, expected_conditions, By, ID

Code Type : Function

Code Difficulty : Intermediate


                
                    
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def find_element_by_id(driver, element_id):
    try:
        return WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, element_id))
        )
    except TimeoutException:
        print(f"Element with ID {element_id} not found")
        return None