Skip to main content
SeleniumDecoded
Back to Challenges

Stale Elements in a Delete Loop

intermediate Python 15 min

Deleting every row in a table throws StaleElementReferenceException after the first deletion. Make the loop robust.

The Scenario

The admin page lists users in a table with a Delete button per row. Clicking Delete shows a confirm dialog; accepting it removes the user and the framework re-renders the whole table body.

The test captures the rows once and iterates. The first delete works. The second iteration throws:

selenium.common.exceptions.StaleElementReferenceException:
stale element reference: stale element not found in the current frame

Your Task

Make the loop delete every row reliably, regardless of how many there are or how the table re-renders, without sleeps.

What Good Looks Like

  • Rows are re-located on every iteration.
  • The loop waits for evidence that the previous delete completed.
  • The loop terminates when no rows remain, and the final assertion still holds.

Your task

Deleting every row in a table throws StaleElementReferenceException after the first deletion. Make the loop robust.

Problem Code
def test_delete_all_rows(driver):
    driver.get("https://app.example.com/admin/users")
    rows = driver.find_elements(By.CSS_SELECTOR, "table.users tbody tr")

    for row in rows:
        row.find_element(By.CSS_SELECTOR, "button.delete").click()
        driver.switch_to.alert.accept()

    assert len(driver.find_elements(By.CSS_SELECTOR, "table.users tbody tr")) == 0

Need Help?

Solution

Try to solve the challenge yourself before revealing the solution.

Lessons that cover this