1

I'm trying to get some elements from a website (private, sorry) and keep getting the dreaded StaleElementReferenceException. I've already incorporated WebDriverWait, but the DOM is still somehow populating so loses the assigned element.

To fix this, I've read to incorporate a try/except block but am having trouble understanding and getting it to work.

What I want is to try for x number of times to assign elements and if any one of them results in a StaleElementReferenceException, go to the next attempt. If no error, exit loop.

What I currently have:

    for p in range (0,5):
        try:
            table = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "*tableID")))
            body = table.find_element(By.CLASS_NAME, "*body class name")
            tableText = body.find_elements(By.TAG_NAME, "tr")
        except StaleElementReferenceException:
            time.sleep(2)
            continue
        break

Any ideas? Thanks!

Retsied
  • 79
  • 8
  • On first sight, your code looks quite ok. What problem do you have using it? You might want to change your sleep statement to an implicit_wait though. – Andreas Apr 23 '21 at 05:53
  • Stale element generally happens during when you swap pages and try to reference an element. – Arundeep Chohan Apr 23 '21 at 06:55

0 Answers0