简体   繁体   中英

Access element inside shadow root in selenium with Java

I am trying to access the "Solve the challenge" button inside the shadow-root (closed) element as shown below:

按钮的 DOM

I have tried:

driver.findElement(By.xpath("//*[@id=\"solver-button\"]")).click();

but it can't access the button because of the shadow-root element.

I am looking for a method to access the button with id solver-button inside the shadow root element.

shadowbutton = driver.execute_script("return document.querySelector('div[class=\"button-holder help-button-holder\"]').shadowRoot.querySelector('button[id=\"solver-button\"]')")
shadowbutton.click()

shadowRoot is not part of the DOM so you first have to find the root element that has the shadow root and then call it using shadowRoot and then call the target element from it.

The element with title as Solve the challenge is within a #shadow-root (open)

shadow_Root


Solution

To click() on the desired element you can use shadowRoot.querySelector() and you can use the following Locator Strategy :

WebElement solverButton = (WebElement) js.executeScript("return document.querySelector('div.button-holder.help-button-holder').shadowRoot.querySelector('button#solver-button')");
solverButton.click();

References

You can find a couple of relevant detailed discussions in:

In case that it suffices to click on the parent element ( <div class="button-holder help-button-holder"></div> ) of the shadow-root element, this post may be helpful.

To perform a mouse click on the help-button-holder element, you can use the moveToElement method as follows:

WebElement buttonHolderElement = driver.findElement(By.xpath("//*[@id=\"rc-imageselect\"]/div[3]/div[2]/div[1]/div[1]/div[4]"));
Actions actionProvider = new Actions(driver);
actionProvider.moveToElement(buttonHolderElement).click().build().perform();

Check the selenium documentation on mouse actions in detail for reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM