Sunday, June 8, 2025

How do I discover the Xpath for the Shadow root component?


In the end, this query comes right down to “How one can discover any component locator for a web site.”

To do that, you should use the Developer Instruments in Chrome (or any trendy net browser).

  1. Open a web site and find the component you need (on this case, a button).
  2. Proper-click on the component and choose “Examine”. The dev instruments will open with the Components tab open. The net component you chose will likely be highlighted within the Components tab.
  3. Proper-click within the Components tab on the highlighted DOM node.
  4. Choose Copy. A submenu will open.
  5. Choose Copy Xpath (or some other choice like Copy Selector for CSS selectors or Copy Full Xpath).

Once I copy Xpath, I get: //*[@id="app"]/div[1]/cmm-cookie-banner//div/div/div[2]/cmm-buttons-wrapper/div/div/wb7-button[2]

Once I copy Selector, I get: div > div > div.cmm-cookie-banner__content > cmm-buttons-wrapper > div > div > wb7-button.button.button--accept-all.wb-button.hydrated

Once I copy Full Xpath, I get: /html/physique/div/div[1]/cmm-cookie-banner//div/div/div[2]/cmm-buttons-wrapper/div/div/wb7-button[2]

We do not know whether or not the OP has tried any of these or not. And we do not know what model of Selenium the OP is utilizing or the browser model. Nonetheless, in Selenium 4 and better, and utilizing Chrome 96 and better, they added a brand new technique WebElement.getShadowRoot()

The Java instance they use is:

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));

SearchContext shadowRoot = shadowHost.getShadowRoot();

WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));

In essence, you can’t use Xpath to find a component within the shadow root. You’ll be able to solely use a CSS Selector. Utilizing this instance code from Seleniem.dev, now you can simply change the CSS Selectors.

What are the #shadow_host and #shadow_content? The #shadow_host returns a reference to an everyday DOM component to make use of, which isn’t within the shadow. The #shadow_content is the component contained in the shadow-root.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com