Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Selenium accept cookies

I need to accept cookies on a specific website but I keep getting the NoSuchElementException. This is the code for entering the website:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time


chrome_options = Options()
driver = webdriver.Chrome(executable_path='./chromedriver', options=chrome_options)

page_url = 'https://www.boerse.de/historische-kurse/Erdgaspreis/XD0002745517'
driver.get(page_url)

time.sleep(10)

I tried accepting the cookie button using the following:

driver.find_element_by_class_name('message-component message-button no-children focusable button global-font sp_choice_type_11 last-focusable-el').click()
driver.find_element_by_xpath('//*[@id="notice"]').click()
driver.find_element_by_xpath('/html/body/div/div[2]/div[4]/div/button').click()

I got the xpaths from copying the xpath and the full xpath from the element while using google chrome.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am a beginner when it comes to selenium, just wanted to use it for a short workaround. Would appreciate some help.

>Solution :

The button Zustimmen is in iframe so first you’d have to switch to the respective iframe and then you can interact with that button.

Code:

driver.maximize_window()
page_url = 'https://www.boerse.de/historische-kurse/Erdgaspreis/XD0002745517'
driver.get(page_url)
wait = WebDriverWait(driver, 30)
try:
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[starts-with(@id,'sp_message_iframe')]")))
    wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Zustimmen']"))).click()
    print('Clicked successfully')
except:
    print('Could not click')
    pass

Imports:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading