我在使用Selenium时遇到了阴影DOM内部元素的问题。这有诀窍吗?我做错了吗?
这是我的各种尝试:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('chrome').build();
driver.get('https://shop.polymer-project.org/');
// Goal is to find shop-app #shadow-root app-header
//
// This is OK; no shadow DOMs
driver.findElement(webdriver.By.css('shop-app'));
// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app /deep/ app-header'));
// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app::shadow app-header'));
// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
return document.querySelector('shop-app /deep/ app-header');
}));
// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
return document.querySelector('shop-app::shadow app-header');
}));
// This fails because:
// WebDriverError: unknown error: Cannot read property 'querySelector' of null
driver.findElement(webdriver.By.js(function() {
return document.querySelector('shop-app').shadowRoot.querySelector('app-header');
}));
// This fails because:
// WebDriverError: unknown error: Cannot read property 'header' of undefined
driver.findElement(webdriver.By.js(function() {
return document.querySelector('shop-app').$.header;
}));
我正在运行节点7.1.0和selenium-webdriver 3.0.1。
答案 0 :(得分:4)
我认为最好使用selenium选择器并注入脚本以获取阴影根:
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()
为了说明这一点,我刚刚在Chrome的下载页面添加了一个可测试的示例,单击搜索按钮需要打开3个嵌套的阴影根元素:
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)
root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)
root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)
search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()
使用其他答案中建议的相同方法有一个缺点,即它对查询进行硬编码,可读性较差,并且您无法将中间选择用于其他操作:
search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()
答案 1 :(得分:2)