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

使用Python Selenium提取href时遭遇ElementClickInterceptedException错误求助

解决Selenium点击Cookie按钮被拦截的问题

针对你遇到的ElementClickInterceptedException错误,以下是几种可行解决方案:

方法1:用JavaScript执行点击

当元素被其他UI层遮挡无法直接点击时,通过JS点击可以绕过拦截:

# 替换原Cookie按钮点击代码
cookie_button = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, "//a[text()='Accept all cookies']"))
)
driver.execute_script("arguments[0].click();", cookie_button)

方法2:滚动到元素可见位置再点击

如果元素处于视口外,先滚动到目标元素位置再点击:

cookie_button = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, "//a[text()='Accept all cookies']"))
)
# 滚动到元素所在位置
driver.execute_script("arguments[0].scrollIntoView(true);", cookie_button)
cookie_button.click()

方法3:设置Headless模式窗口尺寸

Headless模式默认窗口过小,可能导致元素被遮挡,添加窗口大小参数:

# 加入到chrome_options配置中
chrome_options.add_argument('--window-size=1920,1080')

完整修正后的代码

同时注意:分页后元素会重新渲染,需每次循环重新定位下一页按钮;用显式等待替代time.sleep提升稳定性:

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

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1920,1080')  # 设置窗口大小

driver = webdriver.Chrome('chromedriver', chrome_options=chrome_options)
driver.get("https://webgate.ec.europa.eu/rasff-window/screen/search")

# 处理Cookie按钮
cookie_button = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, "//a[text()='Accept all cookies']"))
)
driver.execute_script("arguments[0].click();", cookie_button)

# 点击搜索按钮
search_button = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="search"]/div[3]/div[4]/button'))
)
search_button.click()

counter = 0
while counter <= 50:
    # 等待所有Details链接加载完成
    details = WebDriverWait(driver, 30).until(
        EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(text(),'Details')]"))
    )
    for detail in details:
        print(detail.get_attribute("href"))

    counter += 25
    # 重新定位下一页按钮
    next_page = WebDriverWait(driver, 30).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="main-content"]/app-search-component/div/app-list-component/div/div[3]/mat-paginator/div/div/div[2]/button[2]'))
    )
    next_page.click()
    # 等待页面刷新完成
    WebDriverWait(driver, 10).until(EC.staleness_of(details[0]))

driver.close()

额外说明

  • ElementClickInterceptedException大多因目标元素被弹窗、遮罩层覆盖导致,JS点击是最直接的解决方式。
  • Headless模式必须设置窗口大小,否则会出现大量视口外元素交互问题。
  • 动态分页页面中,上一页的元素对象会失效,必须每次重新定位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:47:31