Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Python's selenium WebDriver has a built-in method named execute_script that allows the execution of JavaScript code on the current webpage. Therefore, the nested shadow DOM of a website can be accessed using the following steps:

  1. Identify the element that contains the shadow DOM you want to access using regular WebDriver methods like find_element_by_id(), find_element_by_css_selector(), or find_element_by_xpath().

  2. Execute JavaScript code using the execute_script() method to get a reference to the shadowRoot of the element:

element = driver.find_element_by_id('my-element')
shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  1. Once you have the shadowRoot reference, you can use regular WebDriver methods to access elements within the shadow DOM. For example:
inner_element = shadow_root.find_element_by_css_selector('#inner-element')

Note that accessing elements inside a shadow DOM requires the use of a special CSS selector syntax to distinguish between elements within the shadow DOM versus elements in the light DOM (outside the shadow DOM). To select an element within the shadow DOM, you must use the /deep/ or ::shadow pseudo-element selectors. For example:

element_within_shadow_dom = shadow_root.find_element_by_css_selector('div /deep/ #my-inner-element')