pythonseleniumselenium-webdriverstaleelementreferenceexception

Python Selenium: Message: stale element reference: element is not attached to the page document


Code trials:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from webdriver_manager.chrome import ChromeDriverManager
import time

# Find Search Element end Type Automation
search_bar = driver.find_element(By.XPATH, "//input[@id='sb_form_q']")
search_bar.send_keys("Automation")
time.sleep(3)

# Click Search Button
search_button = driver.find_element(By.XPATH, "//label[@id='search_icon']//*[name()='svg']")
search_button.click()
time.sleep(3)

# Clear Search Bar
search_bar.clear()

Why when I try to reuse search_bar( e.g:search_bar.clear() ) I always encouter problem:

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

(Session info: chrome=104.0.5112.81)

Help please.

Error snapshot:

enter image description here

Error snapshot:

enter image description here


Solution

  • After you do search_button.click() DOM seem to be updated and so you need to re-define your search_bar:

    # Click Search Button
    search_button = driver.find_element(By.XPATH, "//label[@id='search_icon']//*[name()='svg']")
    search_button.click()
    time.sleep(3)
    
    # Clear Search Bar
    search_bar = driver.find_element(By.XPATH, "//input[@id='sb_form_q']")
    search_bar.clear()