访问shadow DOM中的元素 [英] Accessing elements in the shadow DOM
问题描述
是否可以使用python-selenium 在Shadow DOM 中查找元素?
Is it possible to find elements inside the Shadow DOM with python-selenium?
示例用例:
我有输入
, type =date
:
<input type="date">
我想点击日期选择按钮在右侧并从日历中选择日期。
And I'd like to click the date picker button on the right and choose a date from the calendar.
如果您要检查Chrome开发者工具中的元素并展开日期输入的影子根节点,你会看到按钮显示为:
If you would inspect the element in Chrome Developer Tools and expand the shadow-root node of the date input, you would see the button is appearing as:
<div pseudo="-webkit-calendar-picker-indicator" id="picker"></div>
屏幕截图演示它在Chrome中的外观:
Screenshot demonstrating how it looks in Chrome:
查找选择器按ID按钮结果 NoSuchElementException
:
Finding the "picker" button by id results into NoSuchElementException
:
>>> date_input = driver.find_element_by_name('bday')
>>> date_input.find_element_by_id('picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element
我还尝试使用 :: shadow
和 / deep /
此处建议的定位器:
I've also tried to use ::shadow
and /deep/
locators as suggested here:
>>> driver.find_element_by_css_selector('input[name=bday]::shadow #picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element
>>>
>>> driver.find_element_by_css_selector('input[name=bday] /deep/ #picker')
...
selenium.common.exceptions.NoSuchElementException: Message: no such element
请注意,我可以通过向其发送密钥来更改输入中的日期:
Note that I can change the date in the input by sending keys to it:
driver.find_element_by_name('bday').send_keys('01/11/2014')
但是,我想通过从日历中选择日期来具体设置日期。
But, I want to set the date specifically by choosing it from a calendar.
推荐答案
无法访问本机HTML 5元素的影子根。
There's no way to access the shadow root of native HTML 5 elements.
在这种情况下没用,但使用Chrome可以访问自定义创建的影子根:
Not useful in this case, but with Chrome it's possible to access a custom created shadow root:
var root = document.querySelector("#test_button").createShadowRoot();
root.innerHTML = "<button id='inner_button'>Button in button</button"
<button id="test_button"></button>
然后可以通过以下方式访问root:
The root can then be accessed this way:
var element = document.querySelector("#test_button").shadowRoot;
如果你想用selenium python(chromedriver版本2.14+)自动点击内部按钮:
If you want to automate a click on the inner button with selenium python (chromedriver version 2.14+):
>>> outer = driver.execute_script('return document.querySelector("#test_button").shadowRoot')
>>> inner = outer.find_element_by_id("inner_button")
>>> inner.click()
2015年6月9日更新
这是github上当前Shadow DOM W3C编辑器草案的链接:
This is the link to the current Shadow DOM W3C Editor's draft on github:
http://w3c.github.io/webcomponents/spec/shadow/
If you're interested in browsing the blink source code, this is a good starting point.
这篇关于访问shadow DOM中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!