Home > database >  Selenium Java: Accept All Cookies in ShadowRoot
Selenium Java: Accept All Cookies in ShadowRoot

Time:01-30

This is my web address:

DM :

This is my locator for button accept all:

 @FindBy( xpath = "//button[@data-testid = 'uc-accept-all-button']")
    WebElement cookies;

This is HTML:

enter image description here

I use selenium 4 and Java. I try solution like this :

public void acceptAllCookies( ) {

        cookies = driver.executeScript("return document.querySelector('#usercentrics-root').shadowRoot.querySelector("cookies")");
        cookies.click();
    }

But it does not work. I have error like this:

enter image description here

Any help please. I am a beginner so i see this for first time

I try to add more " marks like in solution I find here but then I get whole executeScript like text.

CodePudding user response:

You would need to use escape sequence in "cookies" See below

cookies = driver.executeScript("return document.querySelector('#usercentrics-root').shadowRoot.querySelector(\"cookies\")");

CodePudding user response:

You have to either use single quotes around cookie in js.executeScript method if your css selector is cookie not java variable. And Cookie defined above is WebElement which can not be directly used while calling executeScript method.

cookies = driver.executeScript("return document.querySelector('#usercentrics-root').querySelector(button[data-testid = 'uc-accept-all-button'])");

And this does not solve your problem, please explain your issue in details.

CodePudding user response:

The element Prihvatite sve button is within #shadow-root (open)

usercentrics


Solution

To click on the desired element you need to use querySelector() and you can use the following locator strategies:

driver.get("https://www.dm.rs/?wt_mc=sea.google.ads_generic.15146192844.132927670207.558370268562");
Thread.sleep(5000);
WebElement element = driver.findElement(By.cssSelector("#usercentrics-root"));
SearchContext context = element.getShadowRoot();
WebElement cookieAcceptAll = context.findElement(By.cssSelector("button[data-testid='uc-accept-all-button']"));
cookieAcceptAll.click();
        

References

You can find a couple of relevant detailed discussions in:

  • Related