Finding shadow DOM text with Selenium and CSS(使用 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 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Selenium 和 CSS 查找阴影 DOM 文本


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01