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:
Error snapshot:
CodePudding user response:
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()
CodePudding user response:
Once you identify the search_button and invoke click on it, the search results appear on the page. This change within the DOM Tree also effects the previously located(found) elements, e.g. search_bar
.
Hence, when you try to refer the previously located search_bar
element, you see the error:
StaleElementReferenceException Message: stale element reference: element is not attached to the page document
Solution
To click, clear or send_keys you have to locate the desired element afresh as follows:
search_bar = driver.find_element(By.XPATH, "//input[@id='sb_form_q']")
Ideally inducing WebDriverWait for the element_to_be_clickable() as follows:
search_bar = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='sb_form_q']")))