我正在尝试从保存在 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 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!