StaleElementReferenceException handling in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import StaleElementReferenceException def test_handle_stale_element(): driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: driver.get('http://example.com/dynamic') # Locate the button button = wait.until(EC.element_to_be_clickable((By.ID, 'refresh-btn'))) # Click the button first time button.click() # Try clicking the button again, handle StaleElementReferenceException try: button.click() except StaleElementReferenceException: # Re-locate the button and click again button = wait.until(EC.element_to_be_clickable((By.ID, 'refresh-btn'))) button.click() # Verify the status message updated after clicks status_msg = wait.until(EC.visibility_of_element_located((By.ID, 'status-msg'))) assert 'updated' in status_msg.text.lower(), f"Expected 'updated' in status message but got '{status_msg.text}'" finally: driver.quit()
This test opens the dynamic page and waits for the button with id 'refresh-btn' to be clickable. It clicks the button once. Then it tries to click the same button again. Because the page content may reload, the button reference can become stale, causing a StaleElementReferenceException. We catch this exception, re-find the button using an explicit wait, and click it again.
Finally, the test waits for a status message element to appear and checks that its text contains the word 'updated', confirming the clicks triggered the expected page behavior.
Using explicit waits ensures the element is ready before interacting. The try-except block handles the stale element gracefully without failing the test.
Now add data-driven testing to click the button multiple times with different expected status messages