Home > Net >  Clicking the "Accept cookies" banner in selenium
Clicking the "Accept cookies" banner in selenium

Time:12-29

im doing my first steps with selenium and encountered a problem with a cookie banner:

Im trying to open the site "https://couchnow.com/" in Selenium and click on the "Alles akzeptieren" Button (which accepts all the cookies).

I tried finding the element by xpath and waiting for the popup to actually appear. This is my code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver.get("https://couchnow.com")
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(driver, 10)
driver.find_elements(By.XPATH, '//*[@id="uccentercontainer"]/div[2]/div/div[1]/div/button"]').click()  


But it throws: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]//div/div/div[2]/div/div[2]/div/div[2]/div/div[1]/div/button"}

But i copied the full xpath directly from the site and dont know why it cant be found.

Thanks in advance.

CodePudding user response:

'Accept Cookies' button is under the shadow DOM.

You can click on that button using the below code:

driver.get("https://couchnow.com")
time.sleep(1)
shadow_root_ele = driver.find_element(By.CSS_SELECTOR, "#usercentrics-root").shadow_root
shadow_root_ele.find_element(By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']").click()

You can refer the below links for Shadow DOM:

https://www.lambdatest.com/blog/shadow-dom-in-selenium/

https://titusfortner.com/2021/11/22/shadow-dom-selenium.html

  • Related