Python Selenium Try/Except x Number of Times for Stale Element

146 Views Asked by At

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!

0

There are 0 best solutions below