Home > Blockchain >  Python/Selenium: Click on cookie consent
Python/Selenium: Click on cookie consent

Time:10-09

I am tring to accept a cookie banner in python using selenium.

So far, I tried a lot to access to the "Accept and continue" (or in german "Akzeptieren und weiter") button, but none of my tries is working.

Some things I already tried out:

driver.get("https://www.spiegel.de/")
time.sleep(5)


try:
    driver.find_element_by_css_selector('.sp_choice_type_11').click() 
except:
    print('css selector failed')

try:
    driver.find_element_by_xpath('/html/body/div[2]/div/div/div/div[3]/div[1]/button').click() 
except:
    print('xpath failed')
    
try:
    driver.find_element_by_class_name('message-component message-button no-children focusable primary-button font-sansUI font-bold sp_choice_type_11 first-focusable-el').click() 
except:
    print('full class failed')
    
try:
    driver.find_element_by_class_name('message-component').click() 
except:
    print('one class component failed')

What else can I try to accept cookies on that website?

CodePudding user response:

The Element Accept and continue is in an Iframe. Need to switch to frame to perform click operation on the same. Try like below:

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

driver = webdriver.Chrome(executable_path="path to chromedriver.exe")
driver.maximize_window()

driver.get("https://www.spiegel.de/")

wait = WebDriverWait(driver,30)

wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Privacy Center']")))

cookie = wait.until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Accept and continue']")))
cookie.click()

CodePudding user response:

While the other answer uses xpath, which is not the preferred locator in Selenium automation, You can use the below css to switch to iframe :

iframe[id^=sp_message_iframe]

Code :

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[id^=sp_message_iframe]")))
WebDriverWait(driver, 20).until((EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='Accept and continue']")))).click()

Imports :

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

It is recommended to have try and except like you've in your code.

  • Related