Home > Software design >  How to bypass the cookies notification popup using Selenium Python
How to bypass the cookies notification popup using Selenium Python

Time:07-09

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.

CodePudding user response:

Have you tried closing out of the popup by having the webdriver find it by xpath and clicking on it?

accept_cookies = driver.find_element(By.XPATH, '/div/div/div/div[2]/div/div[2]/div/div[1]/div/button[2]')
accept_cookies.click()

CodePudding user response:

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/')
    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:

  • Related