AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79593505
Accepted
teeeeee
teeeeee
Asked: 2025-04-26 09:47:28 +0800 CST2025-04-26 09:47:28 +0800 CST 2025-04-26 09:47:28 +0800 CST

无法使用 Selenium WebDriver 关闭网站上的 Cookie 弹出窗口

  • 772

我正在尝试使用 selenium 单击网站autotrader.co.uk的 cookie 弹出窗口上的“全部接受”或“全部拒绝”按钮,但由于某种原因我无法让弹出窗口消失。

这是弹出窗口:

在此处输入图片描述

这是 HTML:

<button title="Reject All" aria-label="Reject All" class="message-component message-button no-children focusable sp_choice_type_13" style="opacity: 1; padding: 10px 5px; margin: 10px 5px; border-width: 2px; border-color: rgb(5, 52, 255); border-radius: 5px; border-style: solid; font-size: 14px; font-weight: 400; color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; width: calc(35% - 20px); background: rgb(5, 52, 255);">Reject All</button>

在此处输入图片描述

我尝试过的代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

path_to_driver = r"C:\path_to_project\chromedriver.exe"
service = Service(executable_path=path_to_driver)

driver = webdriver.Chrome(service=service)
driver.get("https://www.autotrader.co.uk")
time.sleep(5)
WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CLASS_NAME, 'message-component message-button no-children focusable sp_choice_type_13'))).click()

time.sleep(10)
driver.quit()

有人可以帮忙吗?

python
  • 2 2 个回答
  • 97 Views

2 个回答

  • Voted
  1. Best Answer
    Ajeet Verma
    2025-04-26T11:48:45+08:002025-04-26T11:48:45+08:00

    如您所见,弹出窗口嵌入在<iframe>Selenium 中,必须先将驱动程序的上下文切换到该 iframe,然后才能尝试定位或与其中包含的任何元素进行交互。

    等待所需的 iframe 元素可用以切换到它:

    iframe = wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'iframe[id^="sp_message_iframe_"]')))
    

    注意:由于idiframe 的属性似乎是动态生成的,因此建议使用部分匹配策略来定位 iframe,例如CSS selector使用XPath函数contains()或部分匹配策略(https://stackoverflow.com/a/56844649/11179336)

    您可以这样做:

    import time
    from selenium.webdriver import Chrome, ChromeOptions
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    chrome_options = ChromeOptions()
    chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
    driver = Chrome(options=chrome_options)
    
    driver.get("https://www.autotrader.co.uk")
    wait = WebDriverWait(driver, 10)
    
    # wait for the target iframe to get loaded in order to switch to it
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'iframe[id^="sp_message_iframe_"]')))
    
    # click to 'Reject All'
    wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@title="Reject All"]'))).click()
    
    
    time.sleep(5)
    
    • 2
  2. Suramuthu R
    2025-04-27T13:20:21+08:002025-04-27T13:20:21+08:00

    在 Selenium 中使用多个类名时,需要使用 CSS 选择器或 XPath 来代替 By.CLASS_NAME。因此,我在这里使用了:

    1. 更改为 By.CSS_SELECTOR,并带有适当的类链(.class1.class2.class3)
    2. 添加了 JavaScript 点击执行(对于某些元素更可靠)
    3. 添加了适当的错误处理
    4. 由于我们使用了 WebDriverWait,因此删除了多余的 time.sleep(5)
    
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait as wait
    from selenium.webdriver.support import expected_conditions as EC
    
    path_to_driver = r"C:\path_to_project\chromedriver.exe"
    service = Service(executable_path=path_to_driver)
    driver = webdriver.Chrome(service=service)
    
    try:
        driver.get("https://www.autotrader.co.uk")
        
        # Use CSS selector with chained class names
        reject_button = wait(driver, 15).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.message-component.message-button.no-children.focusable.sp_choice_type_13'))
        )
        
        # Scroll into view and click using JavaScript
        driver.execute_script("arguments[0].scrollIntoView(true);", reject_button)
        driver.execute_script("arguments[0].click();", reject_button)
        
        print("Cookie popup closed successfully")
        
    except Exception as e:
        print(f"Error occurred: {str(e)}")
        
    finally:
        time.sleep(5)
        driver.quit()
    

    编辑:

    我没有使用XPath,因为如果我在这里(印度)打开网站,就不会弹出Cookie弹窗。请按照我已更正的以下代码操作XPath。检查XPath按钮的 并将其更改为实际的 即可。

    import time  # Added missing import
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait as Wait
    from selenium.webdriver.support import expected_conditions as EC
    
    path_to_driver = r"C:\path_to_project\chromedriver.exe"
    service = Service(executable_path=path_to_driver)
    driver = webdriver.Chrome(service=service)
    
    try:
        driver.get("https://www.autotrader.co.uk")
        
        # Use XPath to target the reject button by text content
        reject_button = Wait(driver, 15).until(
            EC.element_to_be_clickable((By.XPATH, '//button[contains(., "Reject")]'))
        )
        
        # Click using JavaScript executor
        driver.execute_script("arguments[0].click();", reject_button)
        print("Cookie popup closed successfully")
    
    except Exception as e:
        print(f"Error occurred: {str(e)}")
    
    finally:
        time.sleep(5)
        driver.quit()
    

    如果问题仍然存在,请检查 Cookie 内容是否在 iframe 中。如果是,请进行如下更改:

    iframe = Wait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "iframe")))
    driver.switch_to.frame(iframe)
    
    • 0

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve