Accessing Shadow DOM tree with Selenium

后端 未结 9 816
执念已碎
执念已碎 2020-11-28 09:57

Is it possible to access elements within a Shadow DOM using Selenium/Chrome webdriver?

Using the normal element search methods doesn\'t work, as is to be expected.

9条回答
  •  借酒劲吻你
    2020-11-28 10:41

    For getting the filename of the latest downloaded file in Chrome

    def get_downloaded_file(self):
      filename = self._driver.execute_script("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content  #file-link').text")
      return filename
    

    Usage:

    driver.get_url('chrome://downloads')
    filename = driver.get_downloaded_file()
    

    And for configuring the option for setting the default download directory in selenium for chrome browser, where the corresponding file could be gotten:

    ..
    chrome_options = webdriver.ChromeOptions()
    ..
    prefs = {'download.default_directory': '/desired-path-to-directory'} # unix
    chrome_options.add_experimental_option('prefs', prefs)
    ..
    

提交回复
热议问题