StaleElementReferenceException

Introduction

While working with dynamic web applications, Selenium stores references to web elements after locating them. However, if the webpage changes—for example, due to a page refresh, DOM update, or navigation—the previously stored element may no longer exist in the current page structure.

When Selenium attempts to interact with such an outdated element reference, it raises a StaleElementReferenceException.

This is one of the most common exceptions encountered while automating modern JavaScript-based applications where page elements are frequently refreshed or recreated dynamically.

In this tutorial, you will learn what StaleElementReferenceException is, why it occurs, how to handle it properly, practical examples, common mistakes, best practices, and frequently asked interview questions.


What is StaleElementReferenceException?

StaleElementReferenceException is raised when Selenium attempts to interact with a web element whose reference is no longer attached to the current Document Object Model (DOM).

For example:

Locate Element
        │
        ▼
Store Element Reference
        │
        ▼
Page Refreshes
        │
        ▼
DOM Changes
        │
        ▼
Old Reference Becomes Invalid
        │
        ▼
Perform Action?
        │
        ▼
StaleElementReferenceException

Since Selenium stores the old reference, it cannot interact with the newly created element unless it is located again.


Why Does StaleElementReferenceException Occur?

Some common reasons include:

  • Refreshing the webpage.

  • Dynamic DOM updates.

  • Page navigation.

  • JavaScript re-rendering web elements.

  • AJAX-based content updates.

  • Switching between frames or browser windows.

  • Performing actions on previously located elements after the page changes.


Practical Example

The following example locates an input field, refreshes the webpage, and then attempts to interact with the previously stored element reference.

Since the old reference no longer exists after the refresh, Selenium raises StaleElementReferenceException.

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import (
    StaleElementReferenceException,
)


# Topic: StaleElementReferenceException
# Practice site: https://www.testmuai.com/selenium-playground/simple-form-demo
# Run: pytest -s 61_examples/test_02_stale_element_reference_exception.py
#
# StaleElementReferenceException occurs when a previously located element is
# no longer attached to the current DOM.


def test_stale_element_reference_exception():
    driver = webdriver.Chrome()

    try:
        driver.get(
            "https://www.testmuai.com/selenium-playground/simple-form-demo"
        )

        message_input = driver.find_element(
            By.ID,
            "user-message"
        )

        driver.refresh()  # Old reference becomes stale.

        with pytest.raises(
            StaleElementReferenceException
        ):
            message_input.send_keys(
                "stale reference"
            )

    finally:
        driver.quit()

Output

Chrome browser launched successfully.

Website opened successfully.

Element located successfully.

Page refreshed successfully.

Old element reference became invalid.

StaleElementReferenceException raised successfully.

Exception handled successfully.

Test Executed Successfully.

Note: The exception is expected in this example. PyTest treats the test as successful because pytest.raises() explicitly verifies that StaleElementReferenceException is raised.


Understanding the Code

Import Required Modules

import pytest

from selenium import webdriver
from selenium.webdriver.common.by import By

from selenium.common.exceptions import (
    StaleElementReferenceException,
)

Imports:

  • Selenium WebDriver

  • Locator strategies

  • StaleElementReferenceException

  • PyTest for exception validation


Launch Chrome Browser

driver = webdriver.Chrome()

Creates a new Chrome browser session.


Open the Website

driver.get(
    "https://www.testmuai.com/selenium-playground/simple-form-demo"
)

Opens the Selenium Playground webpage.


Locate the Element

message_input = driver.find_element(
    By.ID,
    "user-message"
)

Selenium stores a reference to the located element.


Refresh the Webpage

driver.refresh()

Refreshing the webpage recreates the DOM.

The previously stored element reference becomes invalid after the refresh operation.


Verify the Exception

with pytest.raises(
    StaleElementReferenceException
):
    message_input.send_keys(
        "stale reference"
    )

Since message_input refers to the old DOM element, Selenium raises StaleElementReferenceException.

If the exception occurs successfully, the test passes.


Close the Browser

driver.quit()

Closes all browser windows and properly ends the WebDriver session.


Execution Flow

Launch Browser
        │
        ▼
Open Website
        │
        ▼
Locate Element
        │
        ▼
Store Element Reference
        │
        ▼
Refresh Webpage
        │
        ▼
DOM Changes
        │
        ▼
Old Reference Becomes Invalid
        │
        ▼
Perform Action
        │
        ▼
Raise
StaleElementReferenceException
        │
        ▼
Verify Exception Using PyTest
        │
        ▼
Close Browser

Automation Testing Example

Suppose an application refreshes user profile information after clicking a button.

profile_name = driver.find_element(
    By.ID,
    "username"
)

driver.refresh()

profile_name.text

This raises:

StaleElementReferenceException

because the stored element reference belongs to the previous DOM.

The solution is to locate the element again after the refresh.

driver.refresh()

profile_name = driver.find_element(
    By.ID,
    "username"
)

Real-World Example

Modern applications built using:

  • React

  • Angular

  • Vue

  • AJAX-based frameworks

frequently recreate DOM elements dynamically.

For example:

Locate Login Button
        │
        ▼
Click Refresh Button
        │
        ▼
DOM Updated Dynamically
        │
        ▼
Old Element Removed
        │
        ▼
New Element Created
        │
        ▼
Perform Action?
        │
        ▼
StaleElementReferenceException

Re-locating the element after the DOM update usually resolves this issue.


Common Mistakes Beginners Make

Reusing Old Element References

Incorrect

username = driver.find_element(
    By.ID,
    "username"
)

driver.refresh()

username.send_keys("admin")

The stored element reference becomes invalid after the refresh.


Better

driver.refresh()

username = driver.find_element(
    By.ID,
    "username"
)

username.send_keys("admin")

Always locate the element again whenever the page changes.


Ignoring Dynamic DOM Updates

Modern applications frequently replace elements dynamically.

Avoid assuming that a previously located element will remain valid throughout the test execution.


Forgetting Explicit Waits

Sometimes elements become stale because new elements are still loading.

Using explicit waits can help synchronize Selenium with dynamic webpages.


Best Practices

  • Locate elements again after page refreshes.

  • Use explicit waits whenever necessary.

  • Avoid storing element references for long durations.

  • Handle dynamic DOM updates appropriately.

  • Prefer locating elements immediately before interacting with them.

  • Understand how modern JavaScript frameworks update the DOM.


Conclusion

StaleElementReferenceException occurs whenever Selenium attempts to interact with a previously located element that no longer exists in the current DOM. Dynamic webpages frequently recreate web elements during refresh operations and AJAX updates, making this exception quite common in real-world automation projects.

Understanding when and why this exception occurs allows automation engineers to build more reliable and maintainable Selenium frameworks by properly synchronizing test execution with application behavior.


Frequently Asked Questions (FAQs)

What is StaleElementReferenceException?

It is raised when Selenium attempts to interact with a web element whose reference is no longer attached to the current DOM.


What causes this exception?

Common causes include:

  • Page refreshes.

  • Dynamic DOM updates.

  • AJAX calls.

  • Page navigation.

  • JavaScript re-rendering.


How can I avoid this exception?

Locate the element again after the webpage changes and use explicit waits whenever necessary.


Does refreshing a webpage cause this exception?

Yes.

Refreshing a webpage recreates the DOM, making previously stored element references invalid.


Why do we use pytest.raises() in this example?

pytest.raises() verifies that Selenium raises the expected exception, allowing us to validate Selenium’s behavior during testing.


Key Takeaways

  • StaleElementReferenceException occurs when Selenium interacts with an outdated element reference.

  • Page refreshes and dynamic DOM updates are common causes of this exception.

  • Previously located elements should be located again after significant page changes.

  • Modern JavaScript applications frequently trigger this exception because of dynamic content updates.

  • Explicit waits can help synchronize Selenium with changing webpages.

  • pytest.raises() can be used to verify expected exceptions during testing.

  • Understanding DOM updates is essential for building robust Selenium automation frameworks.

  • StaleElementReferenceException is one of the most frequently asked Selenium interview topics.