Why does targeting shadow dom elements fail at the 5th element?

前端 未结 2 1581
醉话见心
醉话见心 2020-12-11 10:41

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\' e

相关标签:
2条回答
  • 2020-12-11 11:11

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

    Try it like this:

    def find_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()
    
    0 讨论(0)
  • 2020-12-11 11:15

    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:

    0 讨论(0)
提交回复
热议问题