如何解决检查元素是否显示时出现的Stale Element Reference异常?
问题:点击删除按钮后无法验证按钮是否消失
我希望点击删除按钮后,检查该按钮是否仍显示(测试失败)或已消失(测试通过),但尝试两种方法都触发了报错。
原点击按钮代码
# 查找并点击删除按钮 deleteButton = driver.find_element('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') deleteButton.click() time.sleep(5)
尝试的方法及报错
方法1:调用is_displayed()
if deleteButton.is_displayed(): print("Oh no ! Delete button is always present x_x") else: print("Good ! Delete button is not present anymore")
报错信息:
Traceback (most recent call last): File "c:\Projets Python\Python Basics\tests\Selenium web\add_remove_elements.py", line 35, in <module> if deleteButton.is_displayed(): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webelement.py", line 252, in is_displayed return self.parent.execute_script(f"/* isDisplayed */return ({isDisplayed_js}).apply(null, arguments);", self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webdriver.py", line 405, in execute_script return self.execute(command, {"script": script, "args": converted_args})["value"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webdriver.py", line 345, in execute self.error_handler.check_response(response) File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found (Session info: chrome=116.0.5845.96)
方法2:检查元素text长度
if len(deleteButton.text)>0: print("Yes, the button is not present anymore !") else: print("Ohh, the button is always displayed x_x")
报错信息:
Traceback (most recent call last): File "c:\Projets Python\Python Basics\tests\Selenium web\add_remove_elements.py", line 33, in <module> print("Yes, the button is not present anymore !") ^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webelement.py", line 90, in text return self._execute(Command.GET_ELEMENT_TEXT)["value"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webelement.py", line 395, in _execute return self._parent.execute(command, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\webdriver.py", line 345, in execute self.error_handler.check_response(response) File "C:\Users\hendb\AppData\Roaming\Python\Python311\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found (Session info: chrome=116.0.5845.96)
问题原因
点击删除按钮后,该元素已从DOM中被移除,你之前保存的deleteButton变量是对原DOM元素的引用,此时已失效,再调用它的任何方法都会触发StaleElementReferenceException。
正确解决方案
方案1:重新查找元素并捕获异常
点击后重新定位元素,若找不到则说明元素已消失:
import selenium deleteButton = driver.find_element('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') deleteButton.click() time.sleep(5) # 重新查找元素 try: driver.find_element('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') print("Oh no ! Delete button is always present x_x") except selenium.common.exceptions.NoSuchElementException: print("Good ! Delete button is not present anymore")
方案2:使用find_elements检查元素数量
find_elements会返回匹配的元素列表,若列表为空则元素不存在:
deleteButton = driver.find_element('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') deleteButton.click() time.sleep(5) # 获取所有匹配的元素 delete_buttons = driver.find_elements('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') if len(delete_buttons) > 0: print("Oh no ! Delete button is always present x_x") else: print("Good ! Delete button is not present anymore")
方案3:使用显式等待(推荐,替代time.sleep)
用Selenium的显式等待等待元素消失,比固定休眠更可靠:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException deleteButton = driver.find_element('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]') deleteButton.click() try: # 等待10秒,直到元素不可见或不存在 WebDriverWait(driver, 10).until( EC.invisibility_of_element_located(('xpath','//button[@class="added-manually btn btn-info"][contains(text(),"Delete")]')) ) print("Good ! Delete button is not present anymore") except TimeoutException: print("Oh no ! Delete button is always present x_x")
内容的提问来源于stack exchange,提问作者Hend
相关产品推荐
相关产品推荐

