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:
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()
.
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)
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')
Asked: 2022-12-03 11:00:00 +0000
Seen: 8 times
Last updated: Jul 07 '21