What does a StaleElementReferenceException mean in Selenium WebDriver?
Think about what happens if the page changes after you find an element.
A StaleElementReferenceException occurs when the element you previously found is no longer present in the page's current DOM structure. This often happens after page reloads or dynamic content updates.
What will be the output or result of running the following Selenium Python code snippet?
from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get('https://example.com') element = browser.find_element(By.TAG_NAME, 'h1') browser.refresh() print(element.text) browser.quit()
Consider what happens to the element after the page refresh.
After refreshing the page, the previously found element becomes stale because the DOM is rebuilt. Accessing element.text raises StaleElementReferenceException.
Which assertion correctly verifies that a button's text is 'Submit' after handling a stale element?
from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.common.by import By try: button = driver.find_element(By.ID, 'submit-btn') text = button.text except StaleElementReferenceException: button = driver.find_element(By.ID, 'submit-btn') text = button.text
Focus on the variable holding the button text after retry.
The variable text holds the button's text after retrying the find. Checking assert text == 'Submit' confirms the expected value.
Given the following test code, why does it raise a StaleElementReferenceException?
element = driver.find_element(By.CSS_SELECTOR, '.item') driver.execute_script('document.querySelector(".item").remove()') print(element.text)
Think about what happens when the element is removed from the page.
The JavaScript removes the element from the DOM, so the previously found element reference becomes stale. Accessing element.text then raises the exception.
Which approach is best to handle StaleElementReferenceException in a Selenium test framework to make tests more reliable?
Think about how to recover from dynamic page changes gracefully.
Retrying to find the element when a StaleElementReferenceException occurs is a robust way to handle dynamic page updates and keep tests stable.