[Python] trying to click button in shadow root of html page using selenium and python

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I was trying to make a programm that fulfills a couple of tasks on the gls website but I am struggling to click the accept button of the cookie banner.. I tried selecting it via CSS_SELECTOR as well as XPATH but I cant seem to find the button. Through google search I figured out that I need to select the shadow root first but I still cant seem to find the element? Does anyone have any suggestions or maybe even dealt with usercentrics cookiebanner before?

    Any help is highly appreciated.

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time

    driver = webdriver.Chrome()
    driver.get("https://www.gls-pakete.de/geschaeftlich-versenden")
    try:
    # Shadow Host finden
    shadow_host = driver.find_element(By.XPATH, '//*[@id="usercentrics-cmp-ui"]')
    time.sleep(2)
    print(1)

    # Shadow Root zugreifen
    shadow_root = shadow_host.shadow_root
    time.sleep(2)
    print(2)

    # Element innerhalb des Shadow Roots finden
    element_in_shadow_root = shadow_root.find_element(By.XPATH,
    "//button[contains(text(), 'Alle akzeptieren')]")

    # Mit dem Element interagieren
    print(element_in_shadow_root.text)
    element_in_shadow_root.click() #Added to click the button.
    time.sleep(2) #Added to wait for the page to load after the button click.

    except Exception as e:
    print(f"Error: {e}")

    driver.quit()


    Code runs until after print(2) and returns

    Error: Message: invalid argument: invalid locator
    (Session info: chrome=135.0.7049.85)
    Stacktrace:
    GetHandleVerifier [0x00007FF636755335+78597]
    GetHandleVerifier [0x00007FF636755390+78688]
    (No symbol) [0x00007FF6365091AA]
    (No symbol) [0x00007FF63655EF11]
    (No symbol) [0x00007FF63655F43C]
    (No symbol) [0x00007FF636551C2C]
    (No symbol) [0x00007FF63658712F]
    (No symbol) [0x00007FF636551AB6]
    (No symbol) [0x00007FF636587300]
    (No symbol) [0x00007FF6365AF2BB]
    (No symbol) [0x00007FF636586EC3]
    (No symbol) [0x00007FF6365503F8]
    (No symbol) [0x00007FF636551163]
    GetHandleVerifier [0x00007FF6369FEEED+2870973]
    GetHandleVerifier [0x00007FF6369F9698+2848360]
    GetHandleVerifier [0x00007FF636A16973+2967875]
    GetHandleVerifier [0x00007FF63677017A+188746]
    GetHandleVerifier [0x00007FF63677845F+222255]
    GetHandleVerifier [0x00007FF63675D2B4+111236]
    GetHandleVerifier [0x00007FF63675D462+111666]
    GetHandleVerifier [0x00007FF636743589+5465]
    BaseThreadInitThunk [0x00007FF87C317374+20]
    RtlUserThreadStart [0x00007FF87C45CC91+33]

    Continue reading...

Compartilhe esta Página