是否可以使用 python-selenium 在 Shadow DOM 中查找元素?
示例用例:
我有这个 input
和 type="date"
:
<input type="date">
我想单击右侧的日期选择器按钮,然后从日历中选择一个日期。
如果您检查 Chrome 开发者工具中的元素并展开日期输入的 shadow-root 节点,您会看到该按钮显示为:
<div pseudo="-webkit-calendar-picker-indicator" id="picker"></div>
屏幕截图展示了它在 Chrome 中的外观:
通过 id 找到“选择器”按钮会导致 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/
定位器 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
请注意,我可以通过向其发送 key 来更改输入中的日期:
driver.find_element_by_name('bday').send_keys('01/11/2014')
但是,我想通过从日历中选择来专门设置日期。
最佳答案
无法访问原生 HTML 5 元素的影子根。
在这种情况下没有用,但使用 Chrome 可以访问自定义创建的影子根:
var root = document.querySelector("#test_button").createShadowRoot();
root.innerHTML = "<button id='inner_button'>Button in button</button"
<button id="test_button"></button>
然后可以通过这种方式访问根目录:
var element = document.querySelector("#test_button").shadowRoot;
如果您想使用 selenium python(chromedriver 版本 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 编辑草案的链接:
http://w3c.github.io/webcomponents/spec/shadow/
如果您有兴趣浏览 blink源代码,this is a good starting point .
关于javascript - 访问影子 DOM 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911799/