Sometimes, web elements change or disappear after you find them. Handling StaleElementReferenceException helps your test keep working without crashing.
StaleElementReferenceException handling in Selenium Python
from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.common.by import By try: element = driver.find_element(By.ID, 'example') element.click() except StaleElementReferenceException: element = driver.find_element(By.ID, 'example') # find again element.click()
Use try-except to catch the exception and retry finding the element.
Always find the element again inside the except block to get the fresh reference.
from selenium.webdriver.common.by import By from selenium.common.exceptions import StaleElementReferenceException try: button = driver.find_element(By.CSS_SELECTOR, '.submit') button.click() except StaleElementReferenceException: button = driver.find_element(By.CSS_SELECTOR, '.submit') button.click()
from selenium.webdriver.common.by import By from selenium.common.exceptions import StaleElementReferenceException for i in range(3): try: link = driver.find_element(By.LINK_TEXT, 'Next') link.click() break except StaleElementReferenceException: if i == 2: raise
This script tries to click a button that might reload or change. If the element is stale, it waits a second, finds it again, and clicks it.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import StaleElementReferenceException import time # Setup driver (assuming chromedriver is in PATH) driver = webdriver.Chrome() driver.get('https://example.com/dynamic') try: element = driver.find_element(By.ID, 'dynamic-button') element.click() except StaleElementReferenceException: # Wait a moment for page update time.sleep(1) element = driver.find_element(By.ID, 'dynamic-button') element.click() print('Button clicked successfully') driver.quit()
StaleElementReferenceException means the element is no longer attached to the page.
Always re-find elements after page changes to avoid this error.
Adding a small wait before retrying can help if the page updates slowly.
StaleElementReferenceException happens when the page changes after you find an element.
Use try-except to catch and handle this exception by finding the element again.
Retrying actions after a short wait helps tests run smoothly on dynamic pages.