I am trying to click on 'Alles accepteren' (in english: Accept all) in the cookie pop-up but nothing seems to work. It probably has to do with focusing on the right window. Any help would be appreciated.
My code:
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.hornbach.nl/")
wait = WebDriverWait(driver,30)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='??']")))
cookie = wait.until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Alles accepteren']")))
CodePudding user response:
This is one way of accepting cookies on that website:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import time as t
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('disable-notifications')
chrome_options.add_argument("window-size=1280,720")
webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
wait = WebDriverWait(browser, 20)
url = 'https://www.hornbach.nl/'
browser.get(url)
parent_el = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div[id="usercentrics-root"]')))
parent_el_shadow_root = parent_el.shadow_root
t.sleep(5)
accept_all_button = parent_el_shadow_root.find_element(By.CSS_SELECTOR, 'button[data-testid="uc-accept-all-button"]')
accept_all_button.click()
print('accepted cookies')
Bear in mind this way of locating the shadow root only works for Chrome/chromedriver, and you will need other methods if using Firefox or other browser/driver. Selenium documentation can be found at https://www.selenium.dev/documentation/