Search code examples
python-3.xseleniumxpathcss-selectorswebdriverwait

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


How can I automatically click on the Facebook "Allow all cookies" button? I can't find the part of the code useful for clicking. The link is this 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

My code instead this:

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

I wrote "'button[data-visualcompletion ="accept_button"]', but the error is this.

HTML CODE enter image description here


Solution

  • To click on the Allow all cookies button you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

    • Using CSS_SELECTOR:

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

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