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.
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.
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()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and opens Chrome browser | Browser window opened, ready to navigate | - | PASS |
| 2 | Navigates to 'https://example.com/dynamic-button' | Page with dynamic button loaded | - | PASS |
| 3 | Finds button element with ID 'dynamic-btn' | Button element located in DOM | - | PASS |
| 4 | Clicks the button | Button click triggers page update | - | FAIL |
| 5 | Catches StaleElementReferenceException, retries find and click | Button element refreshed in DOM | - | PASS |
| 6 | Clicks the refreshed button successfully | Button click triggers page update | - | PASS |
| 7 | Finds element with ID 'result-msg' and reads text | Result message displayed: 'Button clicked!' | Assert message text equals 'Button clicked!' | PASS |
| 8 | Test ends and browser closes | Browser closed | - | PASS |