使用 Selenium 和 CSS 查找阴影 DOM 文本

Finding shadow DOM text with Selenium and CSS(使用 Selenium 和 CSS 查找阴影 DOM 文本)
本文介绍了使用 Selenium 和 CSS 查找阴影 DOM 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to locate an input text from input field that is saved in shadow DOM with:

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

但这无济于事.HTML部分

but it does not help. HTML part

<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 中查找元素的最佳方法是什么?在我的情况下,定位器应该链接到元素.

What is the best approach for finding elements in shadow DOM in this case? In my case locator should be linked to element.

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

Update: as suggested I tried:

  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 行上.

推荐答案

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

I was not able to find a solution with Javascripts .shadowRoot option and it is a mystery for me why it does not work. This option works just fine. It input text:

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

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

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

I am still very interested in the approach proposed by PDHide.

这篇关于使用 Selenium 和 CSS 查找阴影 DOM 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

how to remove this error quot;Response must contain an array at quot; . quot;.quot; while making dropdown(如何删除此错误quot;响应必须在quot;处包含数组。创建下拉菜单时(Q;))
Why is it necessary to use `document.createElementNS` when adding `svg` tags to an HTML document via JS?(为什么在通过JS为一个HTML文档添加`svg`标签时,需要使用`Document.createElementNS`?)
wkhtmltopdf print-media-type uses @media print ONLY and ignores the rest(Wkhtmltopdf print-media-type仅使用@media print,而忽略其余内容)
price depend on selection of radio input(价格取决于无线电输入的选择)
calculate price depend on selection without button(根据没有按钮的选择计算价格)
What should I consider before minifying HTML?(在缩小HTML之前,我应该考虑什么?)