Home > Software design >  Python Selenium accept cookies
Python Selenium accept cookies

Time:04-05

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.

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

CodePudding user response:

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
  • Related