Python with Selenium "element is not attached to the page document"

Viewed 36827

I have a python function that should click through all options of a product:

submit_button = driver.find_element_by_id('quantityactionbox')

elementList = submit_button.find_elements_by_tag_name("option")

for x in elementList:
    x.click()

After I clicked 2 elements I get this error:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

Can you maybe tell me why this error appaer and what can I do to go successfully through all elements?

3 Answers

The easy way to overcome many of these types of errors is to just add some sort of delay:

import time

time.sleep(1) 

DOM manipulation after an event is fired usually takes a bit of time so you're not really losing that much of performance.

In my case it was because the page had changed and the element no longer existed but my script was trying to call it. It was not readily obvious because the page did have essentially the same element but it had been reloaded and was therefore, not the exact same element and not available in the current page document. I had to redefine the element after the page was reloaded.

Related