Python Selenium – element is not attached to the page document – once button is clicked

Question:

When I click on an item inside a dropdown list, the item is correctly clicked but the error: "stale element is not attached to the page document" is raised.

I guess this error is raised because of an element I use as changed inside the DOM or has been refreshed, but I didn’t find any solutions for now. Here’s my code:

exam_question_type = self.driver.find_element(By.XPATH, f"//*[name()='svg'][@class='css-19bqh2r']")
exam_question_type.click()
WebDriverWait(self.driver).until(ec.visibility_of_element_located((By.CSS_SELECTOR, 'class=" css-b02ejv-menu"'))
select_question_type = self.driver.find_elements(By.CSS_SELECTOR, 'class="CustomOptionMenu_button__2GnMd"')
for type in select_question_type:
    if type.text == "QCM grid":
        try:
            ActionChains(self.driver).click(type).perform()
        except StaleElementReferenceException:
            pass

What i’m doing wrong?

Asked By: Jin

||

Answers:

Since by clicking on elements inside the dropdown list the page is changing and elements are refreshed you have to grab select_question_type elements again after the refreshing. Something like this:

exam_question_type = self.driver.find_element(By.XPATH, f"//*[name()='svg'][@class='css-19bqh2r']")
exam_question_type.click()
WebDriverWait(self.driver).until(ec.visibility_of_element_located((By.CSS_SELECTOR, 'class=" css-b02ejv-menu"'))
select_question_type = self.driver.find_elements(By.CSS_SELECTOR, 'class="CustomOptionMenu_button__2GnMd"')
for index, type_el in enumerate(select_question_type):
    type_el = select_question_type[index]
    if type_el.text == "QCM grid":
        ActionChains(self.driver).click(type_el).perform()
        WebDriverWait(self.driver).until(ec.visibility_of_element_located((By.CSS_SELECTOR, 'class=" css-b02ejv-menu"'))
        select_question_type = self.driver.find_elements(By.CSS_SELECTOR, 'class="CustomOptionMenu_button__2GnMd"')

Also, I’ve changed the element name from type to type_el since type is a keyword that should not be used for naming of variables.

Answered By: Prophet