pythonselenium-webdrivershadow-root

Selenium: Unable to Click Button Inside Shadow Root


I’m trying to accept the cookies on a website, but the pop-up window doesn’t load properly.

Does anyone know how to resolve this?

Website URL: https://www.guest.wemolo.at/?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjQ4NWIyZWEyLTY2MTItNDU3ZS05YTA4LTRhODBjMTgxNzM4MiJ9.dyAdGEDJ87U-i_lBytN3Y-_kIuJnRKvJKJgVOQ0MlfE

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.maximize_window()
url = 'https://www.guest.wemolo.at/?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjQ4NWIyZWEyLTY2MTItNDU3ZS05YTA4LTRhODBjMTgxNzM4MiJ9.dyAdGEDJ87U-i_lBytN3Y-_kIuJnRKvJKJgVOQ0MlfE'
driver.get(url)

wait = WebDriverWait(driver, 10)
shadow_host = wait.until(EC.presence_of_element_located((By.XPATH, "//button[contains(text(), 'Alles Akzeptieren')]")))
shadow_root = shadow_host.shadow_root
load = shadow_root.find_element(By.XPATH, "//button[contains(text(), 'Alles Akzeptieren')]")
load.click()

I attempted to print the entire webpage, but the cookie consent pop-up doesn’t appear in the print output.

After inspecting the page, I discovered that the pop-up is inside a shadow root. However, I’m unable to access it.

Fixed Solution:

Fixed solution:
`driver = Chrome()
driver.get(URL)
wait = WebDriverWait(driver, 10)
root_element = wait.until(EC.presence_of_element_located((By.ID, "usercentrics-root")))
shadow_root = driver.execute_script("return arguments[0].shadowRoot", root_element)
button = WebDriverWait(shadow_root, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid=uc-accept-all-button]"))
)
driver.execute_script("arguments[0].scrollIntoView();", button)
button.click()

Solution

  • The way to do this is to identify the shadow root then locate the relevant button. The specifics of how to do this vary from website to website. In this particular case it's:

    from selenium.webdriver import Chrome
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    URL = "https://www.guest.wemolo.at/?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjQ4NWIyZWEyLTY2MTItNDU3ZS05YTA4LTRhODBjMTgxNzM4MiJ9.dyAdGEDJ87U-i_lBytN3Y-_kIuJnRKvJKJgVOQ0MlfE"
    
    with Chrome() as driver:
        driver.get(URL)
        wait = WebDriverWait(driver, 10)
        ec = EC.presence_of_element_located
        sel = (By.ID, "usercentrics-root")
        root = wait.until(ec(sel)).shadow_root
        ec = EC.presence_of_element_located
        sel = (By.CSS_SELECTOR, "button[data-testid=uc-accept-all-button]")
        WebDriverWait(root, 10).until(ec(sel)).click()