Selenium WebDriver scenarios to locate shadow DOM elements in a Polymer 3 component on Chrome 117
I'm struggling to automate a web application built with Polymer 3 using Selenium WebDriver. Specifically, I'm trying to click a button that resides inside a shadow DOM. I've confirmed that the button is not visible in the regular DOM tree, which is causing my WebDriver scripts to unexpected result. I've attempted to locate the shadow root and then access the button, but I'm consistently getting a `NoSuchElementException`. Here's the code snippet I've tried so far: ```python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize WebDriver options = webdriver.ChromeOptions() options.add_argument('--headless') # Run in headless mode driver = webdriver.Chrome(options=options) # Navigate to the target page driver.get('https://example.com') try: # Wait for the shadow host element to be present shadow_host = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'my-element')) ) # Access the shadow root shadow_root = driver.execute_script('return arguments[0].shadowRoot', shadow_host) # Try to locate the button inside the shadow DOM button = shadow_root.find_element(By.CSS_SELECTOR, 'button.my-button') button.click() except Exception as e: print(f'behavior: {str(e)}') finally: driver.quit() ``` Unfortunately, the above code throws `NoSuchElementException` when trying to find the button. I've also tried increasing the wait time and ensuring that the shadow DOM is fully loaded before the script attempts to interact with it. The `my-element` selector correctly identifies the shadow host, but accessing the shadow root seems to be where the question lies. Could anyone provide insight into this scenario or suggest alternative methods for interacting with shadow DOM elements in Selenium? I'm using Chrome 117 and the latest version of ChromeDriver. My development environment is Windows 11.