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

如何在Selenium Webdriver中屏蔽广告并处理广告新标签页弹出问题

解决Selenium WebDriver中的广告屏蔽与弹窗标签页问题

Hey there, let's tackle your ad-related headaches in Selenium step by step—we'll cover both blocking ads before they show up, and handling those annoying popup tabs that still slip through.

一、从源头屏蔽广告:配置浏览器参数

The most effective way is to tweak your browser's settings via Selenium options to block ads and popups from loading in the first place. Here's how to do it for Chrome and Firefox:

对于Chrome

Use ChromeOptions to enable popup blocking and restrict ad content:

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

chrome_options = Options()
# 启用内置弹窗拦截
chrome_options.add_argument("--enable-popup-blocking")
# 阻止广告内容加载
chrome_options.add_experimental_option("prefs", {
    "profile.managed_default_content_settings.ads": 2,  # 2代表阻止
    "profile.managed_default_content_settings.popups": 2  # 阻止弹窗
})

driver = webdriver.Chrome(options=chrome_options)

对于Firefox

Use FirefoxOptions to set privacy and popup-blocking preferences:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox_options = Options()
# 阻止页面加载时弹出窗口
firefox_options.set_preference("dom.disable_open_during_load", True)
# 启用Firefox内置跟踪保护(可屏蔽大部分广告)
firefox_options.set_preference("privacy.trackingprotection.enabled", True)

driver = webdriver.Firefox(options=firefox_options)

二、处理已弹出的广告标签页

If some ads still manage to pop up as new tabs, you can write code to detect, close them, and switch back to your main window to keep the script running:

# 先保存主窗口的句柄
main_window = driver.current_window_handle

# 执行可能触发广告弹窗的业务代码
# ... 你的业务逻辑代码 ...

# 获取所有打开的窗口句柄
all_windows = driver.window_handles

# 遍历句柄,找到并关闭广告标签页
for window_handle in all_windows:
    if window_handle != main_window:
        driver.switch_to.window(window_handle)
        # 可选:验证是否为广告页(通过标题或URL判断)
        if "ad" in driver.title.lower() or "advert" in driver.current_url.lower():
            driver.close()

# 切回主窗口继续执行脚本
driver.switch_to.window(main_window)

# 恢复后续脚本执行
# ... 剩余业务代码 ...

三、额外技巧:加载广告屏蔽扩展

如果上述参数还不够,可以直接在浏览器中加载AdBlock Plus这类可信的广告屏蔽扩展。先下载对应浏览器的扩展文件(Chrome是.crx格式,Firefox是.xpi格式),再通过Selenium配置加载:

Chrome示例

# 替换为你本地AdBlock Plus扩展文件的实际路径
chrome_options.add_extension("/users/yourname/downloads/adblock_plus.crx")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:38:38