Lately I’ve been working on a legacy web UI test code base trying to fix issues and upgrade Python3.6 to the latest 3.11 version. Along the way I encountered a lot exceptions like below when the code is trying to get text of a dynamic table content:
selenium.common.exceptions.StaleElementReferenceException: Message: The element with the reference ba734ca8-f168-4a11-8e2d-aec0b79647c9 is stale; either its node document is not the active document, or it is no longer connected to the DOM; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#stale-element-reference-exception
After consulting with chatGPT, I found an effective way to solve the issue which is the Retry Mechanism – Wrap the code that interacts with the element in a try-except block, and catch the StaleElementReferenceException. I have tested and proved it’s working as expected for the dynamic web content.
Here is what it looks like in Python:
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def retry_action(driver, by, value, action, max_retries=3):
for _ in range(max_retries):
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((by, value))
)
return action(element)
except StaleElementReferenceException:
pass
raise Exception("Max retries reached. Unable to perform action.")
# Example usage:
def perform_click(element):
element.click()
driver.get("https://example.com")
retry_action(driver, By.XPATH, "//button[@id='exampleButton']", perform_click)
Yay, another problem down!











