Python Selenium切换iframe接受Cookie操作失败求助
问题排查与修正方案
- 缺少依赖模块导入:代码中使用了
time.sleep()但未导入time模块,运行时会直接抛出模块未找到错误。 - 切换iframe的逻辑不可靠:固定等待5秒无法适配不同网络环境下的iframe加载速度,容易出现iframe还没渲染完成就执行切换操作的报错。
- CSS选择器逻辑错误:你写的选择器包含
cdk-focused、cdk-mouse-focused这类动态交互类,只有当按钮被鼠标聚焦/hover时才会生成,页面初始加载状态下按钮不存在这些类,根本定位不到元素。 - 拼写错误:点击方法写为了
cick(),应为click();最后退出驱动的代码多写了逗号,driver, quit()应为driver.quit()。 - 可选优化:新版Selenium已经不再推荐直接在webdriver初始化时传
executable_path、firefox_options参数,建议改用Service类管理驱动路径,避免后续版本升级报错。
修正后可运行代码
import time from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from seleniumwire import webdriver options = Options() options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' # 旧版Selenium可以保留原写法,新版需要把firefox_options改为options driver = webdriver.Firefox(executable_path=r'C:\geckodriver.exe', options=options) try: driver.get('https://autoscout24.de/') # 显式等待iframe加载完成后再切换,最多等10秒 WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "gdpr-consent-notice"))) # 简化选择器,只匹配固定存在的按钮类,避免依赖动态类 accept_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.solo-button"))) accept_btn.click() # 切回主文档 driver.switch_to.default_content() time.sleep(5) finally: driver.quit()
内容的提问来源于stack exchange,提问作者skizo
相关产品推荐
相关产品推荐

