Selenium + Python · Lesson 33 of 43
Module 33: Shadow DOM
Your task
Implement find_in_shadow_dom(shadow_host, css_selector):
Write it in the editor, then press Check answer (Ctrl + Enter).
Standard XPath cannot pierce Shadow DOM! You must obtain the shadow_root context and use CSS selectors:
# 1. Locate the shadow host element:
shadow_host = driver.find_element(By.CSS_SELECTOR, "custom-search-widget")
# 2. Access shadow_root (Selenium 4 feature):
shadow_root = shadow_host.shadow_root
# 3. Locate elements inside the shadow root using CSS:
input_elem = shadow_root.find_element(By.CSS_SELECTOR, "input.search-field")
input_elem.send_keys("Python Test Automation")Modern Web Components encapsulate styles and DOM nodes inside Shadow DOM trees. In Selenium 4, the element.shadow_root property allows you to access elements inside open Shadow roots natively. Let's conquer Shadow DOM!
Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.
No. The W3C specification strictly requires CSS selectors when querying inside shadow roots.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___