You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9.6+Selenium/Chrome爬虫无法定位Cookie弹窗按钮求助

问题:Cookie弹窗无法定位导致登录按钮被拦截

开发网页爬虫监控数据时,目标页面(https://mygas.airliquide.fr/user/login?)需处理Cookie弹窗与登录验证,使用Selenium时无法定位Cookie弹窗按钮,导致登录按钮被弹窗拦截,触发ElementClickInterceptedException错误。

错误分析

从报错信息可知,Cookie弹窗容器为awe-popkies-content-container,但原代码通过By.NAME定位awe-popkies-banner-bt_agree的方式错误,未匹配到真实按钮元素,导致弹窗未关闭,拦截了登录按钮的点击操作。

解决方案步骤

  1. 精准定位Cookie同意按钮
    通过浏览器开发者工具(F12)选中Cookie按钮,查看其真实属性:实际页面中同意按钮的类名应为awe-popkies-banner-bt_agree,可通过CSS_SELECTOR或XPATH定位,避免盲目猜测属性。

  2. 处理元素可交互性
    使用WebDriverWait等待元素完全可点击,而非仅等待元素存在;若原生点击失败,用JavaScript强制触发点击。

  3. 优化浏览器配置
    添加窗口大小参数,避免元素因窗口过小被隐藏;延长等待时间,适配网络加载延迟。

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.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

# 配置Chrome选项
chrome_options = Options()
# chrome_options.add_argument("--headless")  # 启用无头模式
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--window-size=1920,1080")  # 设置窗口大小,避免元素隐藏

# 初始化Chrome驱动
driver = webdriver.Chrome(options=chrome_options)

# 加载登录页面
driver.get("https://mygas.airliquide.fr/user/login?")

# 处理Cookie弹窗
try:
    # 通过CSS选择器定位同意按钮,等待10秒直到可点击
    cookies_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button.awe-popkies-banner-bt_agree"))
    )
    # 优先原生点击,失败则用JS强制点击
    try:
        cookies_button.click()
    except:
        driver.execute_script("arguments[0].click();", cookies_button)
    print("Cookies accepted")
except Exception as e:
    print(f"Cookies EXCEPTION: {str(e)}")
    pass

# 执行登录操作
username = "<username>"
password = "<password>"

# 等待输入框可见并可交互
username_input = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.NAME, "name"))
)
password_input = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.NAME, "pass"))
)

username_input.send_keys(username)
password_input.send_keys(password)

# 等待登录按钮可点击后执行点击
login_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "edit-submit"))
)
login_button.click()

# 等待页面加载完成(注意title标签为小写)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "title")))

# 抓取页面标题文本
element = driver.find_element(By.TAG_NAME, "title")
text = element.get_attribute("textContent")

print("Scraped element text:", text)

# 关闭浏览器
driver.quit()

额外建议

  • 开发者工具定位元素:直接用浏览器选择器工具查看元素属性,确保定位方式准确。
  • 细化异常捕获:避免用except:捕获所有异常,明确捕获TimeoutException等具体异常,便于排查问题。
  • 适配无头模式:若启用无头模式,需添加--disable-gpu参数,并确保窗口大小设置正确。

内容的提问来源于stack exchange,提问作者smokinjim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:17:01