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

Selenium ElementClickInterceptedException元素被遮挡异常解决方法

报错根因

页面加载时自动弹出的id为webpush-onsite的网页推送订阅iframe浮层覆盖在新闻标签上方,常规点击操作会被浮层拦截,触发ElementClickInterceptedException异常。

修复方案
  • 页面加载完成后优先通过JS直接移除遮挡的iframe浮层,连带移除可能存在的其他模态遮罩,比等待浮层关闭按钮加载后点击的方案稳定性更高
  • 定位到新闻标签后先滚动到元素可视区域中部,避免顶部固定导航栏遮挡,再通过JS触发点击,绕过常规点击的拦截校验
  • 待新闻列表加载完成后提取前2条内容,包含标题、发布时间、正文、配图地址,最终序列化为JSON格式存储
修正后完整代码
import json
import time
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器驱动
driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))
stocks_data = ["AKPL", "NICA"]
all_result = []

for stock_code in stocks_data:
    driver.get(f'https://merolagani.com/CompanyDetail.aspx?symbol={stock_code.lower()}')
    wait = WebDriverWait(driver, 10)

    # 移除遮挡的推送浮层
    driver.execute_script("""
        // 删除遮挡点击的webpush iframe
        document.querySelectorAll('iframe#webpush-onsite').forEach(ele => ele.remove());
        // 删除其他可能存在的遮罩层
        document.querySelectorAll('.modal-backdrop, .push-notification-overlay').forEach(ele => ele.remove());
    """)
    time.sleep(0.5)

    # 定位新闻标签并触发点击
    news_tab = wait.until(EC.presence_of_element_located(
        (By.XPATH, "//li[@id='navNews']//a[@id='ctl00_ContentPlaceHolder1_CompanyDetail1_lnkNewsTab']")
    ))
    # 滚动到元素可视区域中间,避免导航栏遮挡
    driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", news_tab)
    time.sleep(0.3)
    # JS点击绕过元素遮挡校验
    driver.execute_script("arguments[0].click();", news_tab)

    # 提取前2条最新新闻
    news_list = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#divNews .media")))[:2]
    single_stock_data = {"stock_symbol": stock_code, "latest_news": []}
    for news in news_list:
        title = news.find_element(By.CSS_SELECTOR, "h4.media-heading a").text.strip()
        publish_time = news.find_element(By.CSS_SELECTOR, "span.text-muted").text.strip()
        content = news.find_element(By.CSS_SELECTOR, "p").text.strip()
        # 提取配图地址,无配图则为空字符串
        try:
            img_link = news.find_element(By.CSS_SELECTOR, "img.media-object").get_attribute("src")
        except:
            img_link = ""
        single_stock_data["latest_news"].append({
            "title": title,
            "publish_time": publish_time,
            "content": content,
            "image_url": img_link
        })
    all_result.append(single_stock_data)

# 结果写入JSON文件
with open("stock_news.json", "w", encoding="utf-8") as f:
    json.dump(all_result, f, ensure_ascii=False, indent=2)

driver.quit()
补充说明
  • 旧版Selenium提供的find_element_by_*系列定位方法已被官方废弃,代码里统一使用find_element(By.xxx, 定位规则)的新写法,避免版本兼容报错
  • 如果需要将配图同步存储到本地,拿到image_url后发起HTTP请求获取图片二进制流,按文件名写入本地即可
  • 代码里加了短等待时间适配页面渲染节奏,可根据本地网络情况调整时长

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:24:37