Search code examples
javaselenium-webdriverxpath

Selenium Java: click button with CSSselector inside of shadow-root


I have cookie popup from here:

website

which I selected with shadow-root like this:

howto

now I want to click the button with xpath expression like this:

WebElement shadowHost = driver.findElement(By.id("usercentrics-root"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowContent = shadowRoot.findElement(By.cssSelector("button[data-testid='uc-accept-all-button']"));

shadowContent.click();

But selenium always gives me:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"button[data-testid='uc-accept-all-button']"}

How to click the button right?

I am expecting the CSSselector button[data-testid='uc-accept-all-button'] to select the button inside of shadow-root.

Looking for CSSselector "class" sc-dcJsrY.fMlgSq has the same unable to locate element error.

One more question is: can I verify the CSSselector inside of shadow-root in chrome inspect, too? Searching for the CSSselector in chrome inspect gives zero occurrences.

I read here that xpath isn`t supported so I switched to CSSselector: question


Solution

  • Your problem might require simple thread.sleep() or explicitWait; This code worked for me: WebElement el = driver.findElement(By.cssSelector("#usercentrics-root")); SearchContext shadowRoot = el.getShadowRoot(); Thread.sleep(2000); WebElement actual = shadowRoot.findElement(By.cssSelector(".dRvQzh .fMlgSq")); actual.click();