[Python] Selenium Cookie Consent Button Not Clickable Despite Being Visible

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to automate the acceptance of cookie consent banners on websites like "https://www.zalando.de" using Selenium in Python.

    My script searches for various cookie consent button selectors and clicks the appropriate one using JavaScript execution. However, even though the button is present and appears clickable, the click event does not always trigger.

    Here is the relevant Python code

    import logging
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import NoSuchElementException, TimeoutException

    # Set up logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    def handle_cookie_consent(driver):
    selectors = [
    "//button[@data-testid='uc-accept-all-button']",
    "//button[contains(text(), 'Geht klar')]",
    "//button[contains(text(), 'Alles akzeptieren')]",
    "//button[contains(text(), 'Accept all')]",
    "//button[contains(text(), 'Accept')]"
    ]

    try:
    # Check if the cookie consent button is inside an iframe
    iframes = driver.find_elements(By.TAG_NAME, "iframe")
    for iframe in iframes:
    driver.switch_to.frame(iframe)
    for selector in selectors:
    try:
    accept_button = WebDriverWait(driver, 22).until(
    EC.element_to_be_clickable((By.XPATH, selector))
    )
    # Use JavaScript to click the button
    driver.execute_script("arguments[0].click();", accept_button)
    time.sleep(2)
    logger.info(f"Accepted cookie consent using selector: {selector}")
    driver.switch_to.default_content()
    return
    except (NoSuchElementException, TimeoutException):
    driver.switch_to.default_content()
    continue

    # If the button is not inside an iframe, try to find it in the main content
    for selector in selectors:
    try:
    accept_button = WebDriverWait(driver, 2).until(
    EC.element_to_be_clickable((By.XPATH, selector))
    )
    # Use JavaScript to click the button
    driver.execute_script("arguments[0].click();", accept_button)
    time.sleep(2)
    logger.info(f"Accepted cookie consent using selector: {selector}")
    return
    except (NoSuchElementException, TimeoutException):
    continue
    logger.info("No cookie consent button found.")
    except Exception as e:
    logger.error(f"Error handling cookie consent: {e}")

    def main():
    # Set up the WebDriver (e.g., using Chrome)
    driver = webdriver.Chrome()

    try:
    # Open the website
    driver.get("https://www.zalando.de")

    # Handle cookie consent
    handle_cookie_consent(driver)

    # Print the title of the page
    print("Page title is:", driver.title)

    finally:
    # Close the WebDriver
    driver.quit()

    if __name__ == "__main__":
    main()


    Is there a better or more reliable way to handle such cookie banners in Selenium?

    Continue reading...

Compartilhe esta Página