我们正在使用selenium web驱动程序和python进行测试自动化,并尝试使用阴影dom设计自动化html5应用程序。无法识别阴影根下的任何元素。例如。如果我想访问下面给出的阴影根下的任何元素,那我该怎么做呢?任何帮助表示赞赏。
答案 0 :(得分:2)
你可以注入这个执行此操作的javascript,然后在该元素上运行find_element方法:
shadow_section = mydriver.execute_script('''return document.querySelector("neon-animatable").shadowRoot''')
shadow_section.find_element_by_css(".flex")
因为你经常使用你可以创建一个函数,然后上面变成:
def select_shadow_element_by_css_selector(selector):
running_script = 'return document.querySelector("%s").shadowRoot' % selector
element = driver.execute_script(running_script)
return element
shadow_section = select_shadow_element_by_css_selector("neon-animatable")
shadow_section.find_element_by_css(".flex")
在结果元素上你可以放任何方法:
find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector
要查找多个元素(这些方法将返回一个列表):
find_elements_by_name find_elements_by_xpath find_elements_by_link_text find_elements_by_partial_link_text find_elements_by_tag_name find_elements_by_class_name find_elements_by_css_selector
稍后修改:
根元素多次嵌套,第二个嵌套元素在文档中不再可用,但在当前访问的影子根中可用。我认为最好使用selenium选择器并注入脚本只是为了获取阴影根:
def expand_shadow_element(element):
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
return shadow_root
#the above becomes
shadow_section = expand_shadow_element(find_element_by_tag_name("neon-animatable"))
shadow_section.find_element_by_css(".flex")
为了说明这一点,我刚刚在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
selenium.__file__
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()