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

Selenium设置FirefoxProfile下载目录偏好配置未生效问题求助

解决方案
  • 优先检查Selenium版本适配
    Selenium 4.0及以上版本已正式弃用FirefoxProfile类,相关配置需迁移到Options对象中,旧API在新版浏览器驱动中会出现配置不生效的问题。
  • 补充缺失的关键配置项
    当前配置缺少两个强制生效的核心偏好:
    1. browser.download.useDownloadDir:设为True强制浏览器使用指定的下载目录,而非系统临时目录
    2. browser.helperApps.neverAsk.saveToDisk:仅配置了不询问打开文件,还需配置不询问保存到磁盘的MIME类型,避免触发默认保存逻辑
  • 补全zip文件可能的MIME类型
    部分站点返回的zip文件MIME标识并非标准application/zip,可覆盖常见的类型避免匹配失败,例如application/zip,application/x-zip-compressed,application/octet-stream
  • 验证目录权限
    提前打印os.path.dirname(os.path.realpath(__file__))的输出,确认路径存在且当前程序对该目录有读写权限。

修复后的代码示例

Selenium 3.x 版本

import os
from selenium import webdriver

profile = webdriver.FirefoxProfile()
# 指定自定义下载目录
profile.set_preference("browser.download.folderList", 2)
# 强制使用指定下载目录
profile.set_preference("browser.download.useDownloadDir", True)
profile.set_preference("browser.download.manager.showWhenStarting", False)
download_path = os.path.dirname(os.path.realpath(__file__))
profile.set_preference("browser.download.dir", download_path)
# 配置无需询问的保存类型
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/zip,application/x-zip-compressed,application/octet-stream")
# 可选:禁用打开文件询问(根据需要保留)
profile.set_preference("browser.helperApps.neverAsk.openFile", "application/zip,application/x-zip-compressed,application/octet-stream")

driver = webdriver.Firefox(firefox_profile=profile)

Selenium 4.x 版本(推荐)

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

options = Options()
download_path = os.path.dirname(os.path.realpath(__file__))
# 配置下载偏好
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.download.useDownloadDir", True)
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.download.dir", download_path)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/zip,application/x-zip-compressed,application/octet-stream")

driver = webdriver.Firefox(options=options)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:54:06