【问题标题】:Finding shadow DOM text with Selenium and CSS使用 Selenium 和 CSS 查找阴影 DOM 文本
【发布时间】:2021-06-03 15:05:16
【问题描述】:

我正在尝试从保存在 shadow DOM 中的输入字段中查找输入文本:

driver.find_element_by_css_selector("#my_id div:nth-of-type(2)").text 

但这无济于事。 HTML部分

<input _ngcontent-c21="" class="clr-input ng-untouched ng-pristine ng-valid" id="my_id" name="my_id" placeholder="My placeholder namespace" size="40" type="text">
 #shadow-root {user-agent}
  <div pseudo="-webkit-input-placeholder" id="placeholder" style="display: none !important;">My placeholder namespace</div>
  <div>Text I need to find</div>

运气不好也试过这个:

shadow_section = driver.execute_script('''return 
document.querySelector("#my_id").shadowRoot''')
            print(shadow_section.find_element_by_css_selector("div:nth-of-type(2)").text)

在这种情况下,在 shadow DOM 中查找元素的最佳方法是什么? 在我的情况下,定位器应该链接到元素。

更新:按照建议我尝试过:

  shadow_root = driver.execute_script('return arguments[0].shadowRoot', driver.find_element_by_css_selector("#my_id"))
  shadow_root_element = shadow_root(driver.find_element_by_css_selector('div:nth-child(2)'))

但收到了:

TypeError: 'NoneType' object is not callable

shadow_root_element 行。

【问题讨论】:

  • 无法查询user-agentshadowRoots。这些是浏览器特定的实现。所以 Safari 中的 HTML 可能 不同于 Chrome 或 FireFox 中的 HTML。如果尝试在 F12 Elements 中编辑它(双击).. 你不能。
  • 非常感谢。我很难理解。

标签: python html selenium selenium-webdriver shadow-dom


【解决方案1】:
element=driver.execute_script(
    "return document.querySelector('#my_id').shadowRoot.querySelector('div:nth-child(2)')")

你必须使用执行脚本来找到影子根,元素会有你想要的项目。您现在可以使用 element.text 来获取文本

【讨论】:

  • 谢谢。当我执行此操作时,我得到: selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'querySelector' of null
  • 我为 Java 找到了这个答案,试图在 Python stackoverflow.com/questions/56380091/… 中使用它
  • 确保只有一个元素我们的id作为我的id
  • 这个id是唯一的,我之前在Chrome devtools里查过。也许我应该为 shadow DOM 中的元素尝试不同的定位器。
  • 找到该元素,然后将其传递给执行脚本并执行参数[0].shadowRoot
【解决方案2】:

我无法找到带有 Javascripts .shadowRoot 选项的解决方案,为什么它不起作用对我来说是个谜。 这个选项工作得很好。它输入文本:

driver.find_element_by_css_selector("#my_id").get_attribute("value")

driver.find_element_by_id("my_id").get_attribute("value")

我对PDHide提出的方法还是很感兴趣的。

【讨论】:

  • 在您展示的示例中没有名为 value 的属性,那么这将如何工作?
  • 你有网站链接吗?
  • 网站关闭了应用。我发现这个答案很有用 stackoverflow.com/questions/10251525/… 。因此,对于输入元素,我们应该使用“element.get_attribute('value')”。此外,根据我所学到的,它是什么类型的#shadow-root 很重要。就我而言,它是 {user-agent}。我认为在其他情况下,javascript 方法可以正常工作。
  • 我的 HTML 中没有 value 属性。
猜你喜欢
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
相关资源
最近更新 更多