Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 863
Eternal_Sunshine Avatar asked Mar 15 '16 13:03

Eternal_Sunshine


2 Answers

You have the explanation and the solution on The Element is not Attached to the DOM:

A common technique used for simulating a tabbed UI in a web app is to prepare DIVs for each tab, but only attach one at a time, storing the rest in variables. In this case, it's entirely possible that your code might have a reference to an element that is no longer attached to the DOM (that is, that has an ancestor which is "document.documentElement").

If WebDriver throws a stale element exception in this case, even though the element still exists, the reference is lost. You should discard the current reference you hold and replace it, possibly by locating the element again once it is attached to the DOM.

like image 129
Billal Begueradj Avatar answered Sep 20 '22 14:09

Billal Begueradj


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.

like image 38
Wildhammer Avatar answered Sep 18 '22 14:09

Wildhammer