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

能否用Selenium拦截动态广告弹窗?面试自动化框架开发遇阻

解决AutomationExercise站点动态广告弹窗的Selenium方案

针对你在开发添加购物车自动化框架时遇到的偶现动态广告弹窗问题,有几种可靠的处理方式,从根源拦截到适配偶现情况都有覆盖:

1. 拦截广告网络请求(彻底屏蔽)

通过Selenium的CDP(Chrome DevTools Protocol)命令直接阻止广告相关的URL加载,从根源避免弹窗出现。先抓包分析该站点的广告来源域名,然后配置拦截规则:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
driver = webdriver.Chrome(options=options)

# 启用网络拦截并设置屏蔽的广告URL规则
driver.execute_cdp_cmd('Network.enable', {})
driver.execute_cdp_cmd('Network.setBlockedURLs', {
    "urls": [
        "*://*.doubleclick.net/*",
        "*://*.googleadservices.com/*",
        "*://*.advertising.com/*",
        # 可通过浏览器F12抓包补充该站点特有的广告域名
    ]
})

driver.get("https://automationexercise.com/")

这种方法能从根源上阻止广告加载,适合面试时展示对Selenium高级功能的掌握。

2. 通用弹窗关闭逻辑(适配偶现场景)

因为广告触发条件不确定,我们可以封装一个通用的弹窗检查关闭方法,在关键操作前调用,不管弹窗是否出现都不影响流程:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def handle_ad_popup(driver):
    try:
        # 根据你提供的弹窗截图,定位关闭按钮(实际需根据元素属性调整)
        close_button = WebDriverWait(driver, 3).until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'close-modal') or text()='×']"))
        )
        close_button.click()
    except:
        # 无弹窗时直接跳过
        pass

# 示例:进入商品页后先检查关闭弹窗
driver.get("https://automationexercise.com/products")
handle_ad_popup(driver)
# 执行添加购物车操作

这种方法容错性高,不管广告在哪个页面出现,都能自动处理,适合不稳定的弹窗场景。

3. 加载广告拦截浏览器扩展

如果前两种方法效果有限,可以直接加载AdBlock类的浏览器扩展,借助成熟的广告拦截规则屏蔽弹窗:

from selenium.webdriver.chrome.options import Options

options = Options()
# 加载本地下载的AdBlock扩展CRX文件
options.add_extension("adblock_plus.crx")
driver = webdriver.Chrome(options=options)
driver.get("https://automationexercise.com/")

注意需要提前下载对应浏览器的扩展文件,面试时如果允许使用外部资源,这种方法简单高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:54:56