How to bypass the cookies notification popup using Selenium Python

Issue

I have been trying to do some things on this website with the Selenium Webdriver in Python, but every time the Webdriver opens the webpage, a cookie notification appears which I just cant close/bypass. I have already tried using cookie sessions, but that didnt work either. Here is my code (in which I attempted to use the cookies from my main browser):

from http import cookies
from time import sleep
from selenium import webdriver
from csv import DictReader

driver = webdriver.Firefox()
driver.get("https://www.antenne.de/programm/aktionen/pausenhof-konzerte/die-antenne-bayern-pausenhof-konzerte-2022/")

def get_cookies_values(file):
    with open(file, encoding="utf-8-sig") as f:
        dict_reader = DictReader(f)
        list_of_dicts = list(dict_reader)
    return list_of_dicts

cookies = get_cookies_values("cookies.csv")

for i in cookies:
    driver.add_cookie(i)

driver.refresh()

If anyone has any idea how to bypass/close the cookie notification or if you need any more information, let me know.

Solution

The element Alle akzeptieren is within #shadow-root (open).

antenne_de


Solution

To click on Alle akzeptieren you have to use shadowRoot.querySelector() and you can use the following solution:

  • Code Block:

    driver.get('https://www.antenne.de/programm/aktionen/pausenhof-konzerte/die-antenne-bayern-pausenhof-konzerte-2022/')
    time.sleep(3)
    driver.execute_script("""return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""").click()
    

Update

Using WebDriverWait:

driver.get('https://www.antenne.de/programm/aktionen/pausenhof-konzerte/die-antenne-bayern-pausenhof-konzerte-2022/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((driver.execute_script("""return document.querySelector('#usercentrics-root').shadowRoot.querySelector("button[data-testid='uc-accept-all-button']")""")))).click()

References

You can find a couple of relevant discussions in:

Answered By – undetected Selenium

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published