Selenium + Python · Lesson 33 of 43

0/43 done

Module 33: Shadow DOM

33. Shadow DOM Automation with Selenium 4 shadow_root

16 minlesson

Your task

Implement find_in_shadow_dom(shadow_host, css_selector):

  1. Return shadow_host.shadow_root.find_element(By.CSS_SELECTOR, css_selector)

Write it in the editor, then press Check answer (Ctrl + Enter).

Accessing Shadow Roots in Python

Standard XPath cannot pierce Shadow DOM! You must obtain the shadow_root context and use CSS selectors:

python
# 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")

Key Takeaways & Walkthrough Summary

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.

Common Doubts & Lesson Q&A

Can I use XPath inside shadow_root?

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.

Python
Skip