Error "stale element reference: element is not attached to the page document" in Selenium

Hi guys, I’m here again with my very insidious issue.
I have this code part in a while loop

time.sleep(2)
try:
        elements = driver.find_elements(By.TAG_NAME, 'p')
        for e in elements:
            testo = e.text

Many times the program fails on the row “e.text” with this message

“stale element reference: element is not attached to the page document”

As you can see I used “try” function but nothing…
Can someone hel me please?

A brief search for Selenium suggests that the exception you should try to catch is selenium.common.exceptions.StaleElementReferenceException.

Thanks @MRAB , and then what do you suggest to me?
Sorry but I’m a beginner…

What do you want to happen? Do you want it to continue on to the next element? I don’t know what you want to do with the element’s text.

Oh sorry,
If this element makes an error I need that the error doesn’t break the script and the flow moves on in the while loop until the element is finded.
Something like this

while (i<1000) :
    target_Tag_Name = "p"
    time.sleep(2)
    try:
        elements = driver.find_elements(By.TAG_NAME, 'p')
        for e in elements:
           testo = e.text
           print(testo)
    finally:
     i += 1

Thanks.

1 Like

Something like this?

while i < 1000:
    target_Tag_Name = "p"
    time.sleep(2)
    try:
        elements = driver.find_elements(By.TAG_NAME, 'p')
        for e in elements:
           testo = e.text
           print(testo)
    except selenium.common.exceptions.StaleElementReferenceException: # I'm assuming that you have `import selenium`.
        pass

    i += 1
1 Like

Thanks @MRAB ,
I only change

except selenium.common.exceptions.StaleElementReferenceException:

with

except StaleElementReferenceException:

and It seems to work well!!!