Home > Enterprise >  Unable to accept cookies with python/selenium
Unable to accept cookies with python/selenium

Time:05-12

I'm trying to accept a cookie banner, but it doesn't work. The code is the following, what am I doing wrong?

I get the following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element

driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.ticketcorner.ch/event/disney-in-concert-dreams-become-true-hallenstadion-13050005/')

driver.find_element(By.CSS_SELECTOR, '#cmpwelcomebtnyes > a > svg') 
time.sleep(5)
WebDriverWait(driver,25).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#cmpwelcomebtnyes > a > svg'))).click()
time.sleep(5)

CodePudding user response:

If you look the HTML you will see that the button to accept the cookies is contained inside a #shadow-root (open). To get rid of it we can exploit its parent #cmpwrapper in this way

shadow_parent = driver.find_element(By.CSS_SELECTOR, '#cmpwrapper')
outer = driver.execute_script('return arguments[0].shadowRoot', shadow_parent)
inner = outer.find_element(By.CSS_SELECTOR, '#cmpbntyestxt')
inner.click()

CodePudding user response:

If you have Selenium 3 and 4 you'll get a dict error with.

driver.get('https://www.ticketcorner.ch/event/disney-in-concert-dreams-become-true-hallenstadion-13050005/')

shadow_parent = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#cmpwrapper")))
shadow_root_dict  = driver.execute_script('return arguments[0].shadowRoot', shadow_parent)
print(shadow_root_dict)
shadow_root_id = shadow_root_dict['shadow-6066-11e4-a52e-4f735466cecf']
shadow_root = WebElement(driver, shadow_root_id)
shadow_root.find_element(By.CSS_SELECTOR,"#cmpwelcomebtnyes > a").click()
  • Related