如何阅读#shadow-root(用户代理)下的文本

How to read text that is under #shadow-root (user-agent)

我正在使用 Selenium (Python) 来自动化网页。我正在尝试从#shadow-root(用户代理)下的输入字段获取文本。 我使用的 Xpath:

driver.find_element_by_xpath("**//*/p-calendar/span/input**").text

没有返回任何东西。 附上我的 DOM 元素的屏幕截图。 要求:从影子根获取文本:01:01

您可以使用 driver.execute_script 注入 JavaScript 代码,然后 returns ShadowRoot 然后使用 find_element 获取您正在寻找的影子根的子元素。

input_shadow = driver.execute_script('''return document.querySelector("").shadowRoot''')
div_text = inputShadow.find_element_by_tag_name("div").text

$1 - Your element's identifier or selector.

如果您热衷于使用 xpath 查找元素

input_shadow = driver.execute_script('''return $x(\"//*/p-calendar/span/input\")[0]''')
div_text = inputShadow.find_element_by_tag_name("div").text

根据 @hayatoito 的(Shadow DOM 的创建者)comment:

The original motivation of introducing a closed shadow tree is "Never allow an access to a node in a closed shadow tree, via any APIs, from outside", AFAIK. Like that we can not access a node in the internal hidden shadow tree which is used in <video> element, in Blink.

In fact, I designed a closed shadow tree in such a way. If there is a way to access a node in a closed shadow tree, it should be considered as a bug of the spec.

I think it's totally okay to have an API to allow an access in the layer of Chrome apps or extensions. However, for a normal web app, I think the current agreement is "Never allow it".

If we allowed it, that means we do not need a closed shadow tree. Just having an open shadow tree is enough, I think.

进一步 @Supersharp 在他自己在讨论 ​​ 中的回答下方的评论中提到:

#shadow-root (user-agent) are browser vendors native implementation so they are not documented and will never be accessible. Only open Shadow DOM are, as per the specs


WebDriver 视角

最近,@AutomatedTester [Mozilla Corporation 首席培根官 David Burns] 发起了关于 WebDriver - Testability of web components

的讨论

目前 Selenium 团队 开放接受相同的拉取请求。


参考

您可以在以下位置找到一些相关的详细讨论:

  • Need help to click on the element under the shadow Root (closed) type

结尾

在这里你可以找到关于

的相关讨论