使用Selenium时如何将文件下载到项目目录下的temp文件夹
Selenium火狐驱动自定义下载目录配置修改方案
问题根因
- 代码中使用的相对路径
temp/解析基准不固定:火狐浏览器对该路径的解析默认以进程启动时的系统工作目录为基准,而非program.py所在的项目目录,大概率出现路径定位失败。 - 缺少强制使用指定下载目录的配置项:部分火狐版本会忽略自定义路径,回退到默认下载目录。
- 若
temp文件夹被误删,文件写入会直接失败。
修改后的完整代码
import os from selenium import webdriver from selenium.webdriver.firefox.options import Options # 生成temp文件夹绝对路径 project_root = os.path.dirname(os.path.abspath(__file__)) temp_path = os.path.join(project_root, "temp") # 自动创建不存在的temp文件夹 if not os.path.exists(temp_path): os.makedirs(temp_path) profile = webdriver.FirefoxProfile() # 配置自定义下载目录 profile.set_preference("browser.download.folderList",2) profile.set_preference("browser.download.dir", temp_path) # 强制使用指定下载目录 profile.set_preference("browser.download.useDownloadDir", True) profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream") profile.set_preference("browser.helperApps.alwaysAsk.force", False)
关键修改说明
- 用
os模块自动生成temp文件夹的绝对路径,兼容Windows、macOS、Linux不同系统的路径格式,完全避免相对路径解析错误 - 新增
browser.download.useDownloadDir配置为True,强制火狐优先使用自定义的下载目录,不会回退到默认下载路径 - 新增目录存在性校验,temp文件夹不存在时自动创建,避免写入失败
内容的提问来源于stack exchange,提问作者Rikky Bhai
相关产品推荐
相关产品推荐

