【问题标题】:Python Selenium: Message: stale element reference: element is not attached to the page documentPython Selenium:消息:过时的元素引用:元素未附加到页面文档
【发布时间】:2022-08-17 22:08:17
【问题描述】:

代码试验:

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()

为什么当我尝试重用 search_bar(例如:search_bar.clear())时,我总是遇到问题:

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

(会话信息:chrome=104.0.5112.81)

请帮忙。

错误快照:

错误快照:

标签: python selenium selenium-webdriver staleelementreferenceexception


【解决方案1】:

在您执行search_button.click() 之后,DOM 似乎已更新,因此您需要重新定义您的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()

【讨论】:

    【解决方案2】:

    一旦你确定搜索按钮并调用点击它,搜索结果出现在页面上。 DOM Tree 中的这种变化也会影响先前定位(找到)的元素,例如search_bar.

    因此,当您尝试引用先前定位的search_bar元素,您会看到错误:

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

    解决方案

    点击,清除或者发送键您必须重新定位所需的元素,如下所示:

    search_bar = driver.find_element(By.XPATH, "//input[@id='sb_form_q']")
    

    理想情况下,为element_to_be_clickable() 诱导WebDriverWait 如下:

    search_bar = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='sb_form_q']")))
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2020-11-13
      • 1970-01-01
      • 2019-09-30
      • 2018-10-23
      • 2020-10-30
      • 2019-02-03
      • 2021-12-15
      • 2021-05-10
      相关资源
      最近更新 更多