0
0
Selenium Pythontesting~10 mins

StaleElementReferenceException handling in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, tries to click a button that may become stale, and handles the StaleElementReferenceException by retrying the element lookup and click. It verifies that the button click succeeds without error.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import StaleElementReferenceException
import time

def test_click_button_with_stale_handling():
    driver = webdriver.Chrome()
    driver.get('https://example.com/dynamic-button')
    
    max_attempts = 3
    attempts = 0
    while attempts < max_attempts:
        try:
            button = driver.find_element(By.ID, 'dynamic-btn')
            button.click()
            break  # success
        except StaleElementReferenceException:
            attempts += 1
            time.sleep(1)  # wait before retry
    else:
        assert False, 'Button remained stale after retries'
    
    # Verify some result after click
    message = driver.find_element(By.ID, 'result-msg').text
    assert message == 'Button clicked!', f'Unexpected message: {message}'
    driver.quit()
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts and opens Chrome browserBrowser window opened, ready to navigate-PASS
2Navigates to 'https://example.com/dynamic-button'Page with dynamic button loaded-PASS
3Finds button element with ID 'dynamic-btn'Button element located in DOM-PASS
4Clicks the buttonButton click triggers page update-FAIL
5Catches StaleElementReferenceException, retries find and clickButton element refreshed in DOM-PASS
6Clicks the refreshed button successfullyButton click triggers page update-PASS
7Finds element with ID 'result-msg' and reads textResult message displayed: 'Button clicked!'Assert message text equals 'Button clicked!'PASS
8Test ends and browser closesBrowser closed-PASS
Failure Scenario
Failing Condition: Button element remains stale after 3 retries
Execution Trace Quiz - 3 Questions
Test your understanding
What exception does the test handle when the button becomes stale?
ATimeoutException
BNoSuchElementException
CStaleElementReferenceException
DElementNotInteractableException
Key Result
When elements on a page update dynamically, they can become stale. Handling StaleElementReferenceException by retrying element lookup and action helps make tests more reliable.