使用Python Selenium访问Shadow DOM树的问题

vql8enpb  于 2023-05-29  发布在  Python
关注(0)|答案(1)|浏览(165)

bounty将在5天内到期。此问题的答案有资格获得+50声望奖励。Tory希望引起更多关注这个问题。

我正在尝试访问页面上的深度嵌套Shadow DOM:https://express.adobe.com/tools/remove-background
在其中一个影子DOM中是我需要访问的元素(文件输入元素)。
我目前正在尝试这个:

sptheme = driver.find_element(By.TAG_NAME, "sp-theme")
container = sptheme.find_element(By.ID, "quick-task-container")
shadow_root = container.find_element(By.TAG_NAME, "cclqt-remove-background").shadow_root
sptheme2 = shadow_root.find_element(By.TAG_NAME, "sp-theme")

我得到这个错误是由于上面的第四行:

selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator

Element Hierarchy(我相信)到我希望访问的元素:

-tag sp-theme
    -id quick-task-container
      -tag cclqt-remove-background
         -SHADOW DOM
           -tag sp-theme
             -tag cclqt-workspace
               -tag cclqt-image-upload
                 -SHADOW DOM
                   -class cclqt-file-upload__container 
                     -this should be where the element is, with the ID: 'file-input'
jqjz2hbq

jqjz2hbq1#

您可以利用execute_script()方法执行JavaScript代码来与Shadow DOM进行交互。下面是一个如何在嵌套的Shadow DOM中访问file input元素的示例:

# Find the outermost shadow host element
sptheme = driver.find_element(By.TAG_NAME, "sp-theme")

# Execute JavaScript to get the shadow root of the outermost shadow host element
shadow_root = driver.execute_script("return arguments[0].shadowRoot", sptheme)

# Find the nested shadow host element within the shadow root
sptheme2 = shadow_root.find_element(By.TAG_NAME, "sp-theme")

# Execute JavaScript to get the shadow root of the nested shadow host element
nested_shadow_root = driver.execute_script("return arguments[0].shadowRoot", sptheme2)

# Find the file input element within the nested shadow root
file_input = nested_shadow_root.find_element(By.ID, "file-input")

在上面的代码中,我们首先找到标记名为“sp-theme”的最外面的shadow host元素。然后,我们执行JavaScript来检索它的影子根。接下来,我们使用find_element()在影子根中找到嵌套的影子宿主元素,并再次执行JavaScript来检索其影子根。最后,我们可以使用其ID在嵌套的影子根中找到文件输入元素。
使用Selenium访问Shadow DOM元素有点复杂,因为Shadow DOM与主DOM隔离。通过执行JavaScript来检索影子根,您可以访问其中的元素。

相关问题