Search code examples
pythonseleniumselenium-webdriverstaleelementreferenceexception

Getting error "Message: stale element reference: element is not attached to the page document".what i am doing wrong


connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']")
        print(len(connections))
for connection in connections:
    if connection.text == "XXX":
        connection.click()
        break

I am getting the following error in the if statement:

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


Solution

  • Stale element exception happen when properties of element on which your script is trying to perform some operation is changed. If you want to click a span with text "XXX" you can directly click on that:

    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[span[text()='XXX']]")))
    

    If your requirement is to loop trough all such elements then:

    connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']")
            print(len(connections))
    for i in range(len(connections)):
    
        connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']") #Created Fresh element list, so it wont be stale 
         if connections[i].text == "XXX"
             connections[i].click
             break