Selenium + Python · Lesson 25 of 43

0/43 done

Module 25: Handling Dynamic Web Elements

25. Handling Dynamic Elements, Spinners & Stale References

16 minlesson

Your task

Implement wait_for_spinner_gone(driver, spinner_locator):

  1. Return WebDriverWait(driver, 10).until(EC.invisibility_of_element_located(spinner_locator)).

Write it in the editor, then press Check answer (Ctrl + Enter).

Handling Spinners & Stale Elements in Python

python
from selenium.common.exceptions import StaleElementReferenceException

# Wait for spinner disappearance:
WebDriverWait(driver, 10).until(
    EC.invisibility_of_element_located((By.CSS_SELECTOR, ".spinner-icon"))
)

# Retry loop for stale element references:
def click_with_retry(driver, locator, max_attempts=3):
    for _ in range(max_attempts):
        try:
            driver.find_element(*locator).click()
            return
        except StaleElementReferenceException:
            pass
    raise RuntimeError(f"Element remained stale: {locator}")

Key Takeaways & Walkthrough Summary

Modern Single Page Applications constantly re-render components, resulting in dynamic IDs and StaleElementReferenceException. In this lesson, you will learn to wait for spinner disappearance and handle stale elements with clean retry logic. Let's tackle dynamic elements!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What causes StaleElementReferenceException in Python?

The Python element object references a DOM node that was detached or replaced by JavaScript after an AJAX reload.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip