Skip to content Skip to sidebar Skip to footer

Why Does Targeting Shadow Dom Elements Fail At The 5th Element?

Recently asked how to target elements in chrome settings here: How to edit chromes search and homepage with selenium/python? I was told I should use 'shadow dom' elements, so I wen

Solution 1:

It looks like you just have to recursively traverse the elements with shadowRoots.

Try it like this:

deffind_in_shadow_dom(css):
  return driver.execute_async_script("""
    const traverse = e => {
      let el
      if(el = e.querySelector('""" + css + """')){
        arguments[0](el)
      }
      [...e.querySelectorAll('*')].filter(e => e.shadowRoot).map(e => traverse(e.shadowRoot))
    }
    [...document.querySelectorAll('*')].filter(e => e.shadowRoot).map(e => traverse(e.shadowRoot))
    arguments[0](null)
  """)

input = find_in_shadow_dom('#searchInput')
input.send_keys('testing')

Edit: Notes for settings page..

control = find_in_shadow_dom('[label="Open a specific page or set of pages"]')
# don't forget to scroll into view
driver.execute_script("arguments[0].scrollIntoView(true)", control)
control.click()

Solution 2:

AFAIK, there is no such limit to access the shadow element. You should be good to access them until you provide the correct shadow tree elements.

Refer to answer here for detailed explanation. It's informative and detailed..

Here is the js that you can pass and return the element

input = driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-toolbar#toolbar').shadowRoot.querySelector('cr-toolbar#toolbar').shadowRoot.querySelector('cr-toolbar-search-field#search').shadowRoot.querySelector('input#searchInput')")
input.send_keys('testing')

Screenshot:enter image description here

Post a Comment for "Why Does Targeting Shadow Dom Elements Fail At The 5th Element?"