Search code examples
c#seleniumwebdrivershadow-dom

Selenium Webdriver with Shadow DOM


While using Selenium Webdriver in C#, I get an exception when trying to select an element that exists under Shadow DOM.

The exception I am getting is: NoSuchElementException

How would you suggest to use Selenium with Shadow DOM?

Thanks,

Michal

img


Solution

  • Try to locate your element like this:

    driver.FindElement(By.CssSelector('selector_otside_shadow_root /deep/ selector_inside_shadow_root')); 
    

    in your case it would be:

    driver.FindElement(By.CssSelector('app-home /deep/ #itemName1'));
    

    You can test this approach in chrome://downloads/ link with this css_selector:

    downloads-manager /deep/ downloads-item /deep/ [id=file-link]
    

    in dev tools. As you can see there was needed to pass two shadow-root elements, so make sure that you have only one shadow-root element or use multiple /deep/ like in example above.

    or you can use JavasciptExecutor like this:

    IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
    var element = js.ExecuteScript("return document.querySelector('selector_outside_shadow_root').shadowRoot.querySelector('selector_inside_shadow_root');");
    
    • Note: the first suggestion as far I know works only in Chrome, if you want a cross browser solution - use the second one.