Selenium 获取 Shadow DOM 内部元素时出现 StaleElementReferenceException
的问题排查与解决
在使用 Selenium 操控浏览器自动化测试无界微前端(Wujie)应用的过程中,我们遇到了一个奇特的问题:无法通过常规方式获取 Shadow DOM 中的元素,抛出 StaleElementReferenceException
异常。本文将详细记录这次问题的排查过程、分析成因,并提供有效的解决方案。
一、问题现象
我们在尝试通过 Selenium 获取某个自定义 Web Component(如 <wujie-app>
)内部 Shadow DOM 中的 <input>
元素时,出现了如下异常:
StaleElementReferenceException: Message: stale element reference: stale element not found
代码示例如下:
chrome = Chrome()
chrome.get(url)
host = chrome.find_element("css selector", "wujie-app")
shadow_root = host.shadow_root
element = shadow_root.find_element("css selector", "input")<