如何使用 Selenium 和 Python 自动点击 "Accept cookies" 按钮

How to automatically click on the "Accept cookies" button using Selenium and Python

如何自动点击 Facebook 的“允许所有 cookie”按钮?我找不到对点击有用的代码部分。 link 就是这个 https://www.facebook.com/privacy/consent/user_cookie_choice/?source=pft_user_cookie_choice

NOT A LINK: To view the cookie button, you must be logged in with Facebook, because there is a cookie button both before logging in and after logging in. In this case it is the cookie button after login

我的代码是这样的:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-visualcompletion="accept_button"]'))).click()

我写了“'button[data-visualcompletion ="accept_button"]',但错误是这样的。

HTML 代码

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
driver.get('https://www.facebook.com/privacy/consent/user_cookie_choice/?source=pft_user_cookie_choice')
WebDriverWait(driver, 86400).until(lambda x: x.find_element_by_xpath('/html/body/div[3]/div[2]/div/div/div/div/div[3]/button[2]')).click()

不确定您在哪里找到该定位器,因为据我所知该元素不是按钮。我看到了两个用于查找此元素的选项。

ele = driver.find_element_by_css_selector("div[aria-label='Allow all cookies']")

# or

ele = driver.find_element_by_xpath(span[contains(text(), 'Allow all cookies')])

要单击 允许所有 cookies 按钮,您必须诱导 WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[aria-label='Consenti tutti i cookie'] span span"))).click()
    
  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Consenti tutti i cookie']"))).click()