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

如何阻止Firefox在Selenium自动化测试中打开已下载文件

解决Firefox Selenium下载文件时自动打开新标签页的问题

你需要在现有配置基础上添加几个关键偏好设置,来阻止Firefox自动打开下载的文件:

  • 添加pdfjs.disabled并设为True:禁用Firefox内置PDF查看器,避免PDF在浏览器标签页打开
  • 添加plugin.disable_full_page_plugin_for_types,指定要阻止打开的文件MIME类型
  • 添加browser.helperApps.alwaysAsk.force设为False,确保不会触发下载询问弹窗
  • 补充可能遗漏的MIME类型(比如部分CSV文件会用application/vnd.ms-excel类型)

修改后的完整代码如下:

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

firefox_options = Options()

# 基础下载配置
firefox_options.set_preference("browser.download.folderList", 2)
firefox_options.set_preference("browser.download.manager.showWhenStarting", False)
firefox_options.set_preference("browser.download.dir", "/tmp")
firefox_options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf,text/csv,application/vnd.ms-excel")

# 新增的阻止自动打开配置
firefox_options.set_preference("pdfjs.disabled", True)
firefox_options.set_preference("plugin.disable_full_page_plugin_for_types", "application/pdf,text/csv,application/vnd.ms-excel")
firefox_options.set_preference("browser.helperApps.alwaysAsk.force", False)

driver = Firefox(options=firefox_options)

配置说明:

  • pdfjs.disabled:Firefox默认用内置工具打开PDF,禁用后会直接下载文件而不打开标签页
  • plugin.disable_full_page_plugin_for_types:限制浏览器不使用插件全屏打开指定类型的文件
  • browser.helperApps.alwaysAsk.force:强制关闭下载确认弹窗,确保文件直接保存到指定目录
  • 补充application/vnd.ms-excel是适配部分网站返回CSV文件的特殊MIME类型,避免遗漏

如果问题仍存在,可以通过浏览器开发者工具的网络请求查看目标文件实际返回的MIME类型,将对应类型补充到配置中即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:57:03