有人知道如何使用SeleniumWebDriver识别ShadowDOM web元素吗?

2024-05-15 07:54:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我们正在使用SeleniumWeb驱动程序和python实现测试自动化,并尝试使用影子dom设计自动化html5应用程序。无法识别阴影根下的任何元素。例如,如果我想访问下面给出的阴影根下的任何元素,那么我该怎么做?感谢您的帮助

enter image description here


Tags: 应用程序元素驱动程序html5dom阴影影子seleniumweb
1条回答
网友
1楼 · 发布于 2024-05-15 07:54:26

您可以插入执行此操作的javascript片段,然后在该元素上运行find_元素方法:

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

To find multiple elements (these methods will return a list):

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()

相关问题 更多 >