Python+Selenium+Firefox修改下载目录问题求助(Mac环境)
Firefox自定义下载目录配置修复方案
针对你的配置问题,以下是几个关键修复点和调整后的代码:
- 修正参数类型:
browser.download.folderList需要传入整数而非字符串,原代码中的'2'会被Firefox忽略,改为2才能启用自定义目录模式。 - 强制启用自定义目录:添加
browser.download.useDownloadDir并设为True,确保Firefox严格使用指定路径。 - 补充CSV的MIME类型:部分网站返回的CSV文件可能使用
text/comma-separated-values或application/csv类型,仅设置text/csv可能无法匹配,需补充完整。 - Mac环境适配:可选添加关闭下载完成提示的配置,避免弹窗干扰。
修改后的代码
from selenium import webdriver from selenium.webdriver.firefox.options import Options import os @given("First step") def step_impl(context): download_path = "/Users/this/is/the/absolute/path/downloads" # 提前创建目录(避免路径不存在导致失败) os.makedirs(download_path, exist_ok=True) options = Options() 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) # 覆盖常见CSV相关MIME类型 options.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,text/comma-separated-values,application/csv") # Mac下关闭下载完成提示弹窗 options.set_preference("browser.download.manager.showAlertOnComplete", False) context.driver = webdriver.Firefox(options=options)
额外验证步骤
- 确认
download_path是真实存在的绝对路径,替换为你本地的实际路径。 - 检查目标目录的读写权限,确保PyCharm运行的进程能正常写入文件。
- 若仍不生效,可通过浏览器开发者工具的「网络」面板,查看下载文件的
Content-Type响应头,确认该类型已包含在browser.helperApps.neverAsk.saveToDisk的配置中。
内容的提问来源于stack exchange,提问作者Faith Berroya
相关产品推荐
相关产品推荐

