Cookie 横幅在被接受后立即重新出现

Cookie banner reappears immediately after being accepted

我正在尝试等待网站上出现 cookie 横幅并点击接受。 cookie 横幅似乎被检测到并被接受,但它随后重新出现并阻止执行任何进一步的操作,直到再次执行该过程。我想不出为什么。

有没有一种方法可以让我在继续抓取页面之前不断接受 cookie,直到此横幅不出现为止?

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%7CSEQUENCING&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()

一个快速的解决方法是将 cookie clicker 包装在一个函数中,并在需要时使用它。

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%7CSEQUENCING&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()

此外,如果您希望它稳健,请像您一样包含 webdriverwait。另外,您可以尝试先检查是否有元素(接受 cookie 按钮),然后单击它,否则 pass.