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

I EXECUTE THIS to auto connect in linkedin but when it comes to the page number 5 they told me :selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document ?

    def repeat():
    all_buttons: list[WebElement] = driver.find_elements_by_tag_name("button")
    connect_buttons = [btn for btn in all_buttons if btn.text == "Connect"]
    for btn in connect_buttons:
        driver.execute_script("arguments[0].click();", btn)
        time.sleep(2)
        send = driver.find_element_by_xpath("//button[@aria-label='Send now']")
        driver.execute_script("arguments[0].click();", send)
        time.sleep(2)
        close = driver.find_element_by_xpath("//button[@aria-label='Dismiss']")
        driver.execute_script("arguments[0].click();", close)
        time.sleep(10)
    follow_buttons = [btn2 for btn2 in all_buttons if btn2.text == "Follow"]
    for btn2 in follow_buttons:
        driver.execute_script("arguments[0].click();", btn2)
        time.sleep(10)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(10)
    Next_button = driver.find_element_by_xpath("//button[@aria-label='Next']")
    driver.execute_script("arguments[0].click();", Next_button)
    time.sleep(5)


while True :
    repeat()...


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source