pythonselenium-webdriver

How to reach inner button inside a inner open shadow root with selenium


a webpage has this HTML

<custom-tag1 class data-component-key="..." ...>
 #shadow-root (open)
  <div class="...">
    <custom-tag2 ...>
     #shadow-root (open)
     <button class="button-download" style="background: transparent; border: 0;">
     </button>
    </custom-tag2>
  </div>
</custom-tag1>

I can reach the first shadow root by doing

outer_host = driver.find_element_by_css_selector("custom-tag1")
outer_shadow_root = driver.execute_script("return arguments[0].shadowRoot", outer_host)

but then I can't repeat the process. The outer_shadow_root is a ShadowRoot class. It has a find_element method, but I fail to locate custom-tag2

No invocation of the find_element by any locator works

Any ideas?


Solution

  • Native shadow locator supports only few locator strategies (ID, NAME, CLASS_NAME and CSS_SELECTOR). Go with CSS Selector like below is working for me enter image description here

    custom_tag_1_root = driver.find_element(By.CSS_SELECTOR, 'custom-tag1').shadow_root
    custom_tag_2_root = custom_tag_1_root.find_element(By.CSS_SELECTOR, 'custom-tag2').shadow_root
    download = custom_tag_2_root.find_element(By.CSS_SELECTOR, '.button-download')
    download.click()
    

    if difficult to find CSS Selector and only Xpath can be constructed then go with third party libraries to handle shadow dom.