Home > database >  Cookie banner reappears immediately after being accepted
Cookie banner reappears immediately after being accepted

Time:03-10

I am attempting to wait for the presence of a cookie banner on a website and hit accept on it. The cookie banner seems to be detected and is accepted, but it then reappears and prevents any further actions from being carried out until the process is carried out again. I cannot work out the reason for why.

Is there a way that I can continually accept the cookies until this banner does not appear before I continue scraping the page?

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

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
wait = WebDriverWait(driver, 20)
page = "https://www.sainsburys.co.uk/shop/gb/groceries/meat-fish/meatandfish-essentials#langId=44&storeId=10151&catalogId=10241&categoryId=474595&parent_category_rn=13343&top_category=13343&pageSize=60&orderBy=TOP_SELLERS|SEQUENCING&searchTerm=&beginIndex=0&facet="
driver.get(page)


# wait for cookies banner

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#onetrust-accept-btn-handler"))).click()

CodePudding user response:

One quick workaround is to wrap the cookie clicker in a function and use it whenever required.

def cookie_handler():
    try:
        driver.find_element(By.ID, "onetrust-accept-btn-handler").click()
    except:
        pass

# this is the main code and uses the cookie_handler fucntion as required.
driver.get("https://www.sainsburys.co.uk/shop/gb/groceries/meat-fish/meatandfish-essentials#langId=44&storeId=10151&catalogId=10241&categoryId=474595&parent_category_rn=13343&top_category=13343&pageSize=60&orderBy=TOP_SELLERS|SEQUENCING&searchTerm=&beginIndex=0&facet=")
time.sleep(5)
cookie_handler()
time.sleep(3)
driver.find_element(By.LINK_TEXT, "Nectar").click()
time.sleep(2)
cookie_handler()
time.sleep(2)

driver.quit()

Additionally, if you want this to be robust, include webdriverwait as you did. Also, you can try to check if there is an element first (Accept cookie button) and then click it, else pass.

  • Related