如何使用Selenium ChromeDriver与Chrome将文件下载到自定义指定路径
问题根因
你的代码存在2处明确错误,和1处可选适配问题,不是路径填写错误:
- 核心错误1:Chrome下载路径的偏好配置键名写错了,你写的是
download.default_dictionary,正确的键名应该是download.default_directory - 核心错误2:Windows路径的反斜杠没有做转义处理,Python字符串里单个
\会被识别为转义字符,导致实际读取的路径和你预期不一致 - 适配问题:新版本Selenium已经废弃
chrome_options参数,统一使用options传递配置,部分旧版本也会因为这个参数识别异常导致配置不生效
修正后的完整代码
import time import os from selenium import webdriver from selenium.webdriver.chrome.options import Options chromeOptions = Options() # 先判断目标文件夹是否存在,不存在就新建,避免Chrome识别无效路径 fallback到默认下载目录 target_path = r"C:\DownloadedAutomationFiles" if not os.path.exists(target_path): os.makedirs(target_path) # 修正配置键名 + 用原始字符串处理路径 + 额外加禁止下载弹窗的配置避免干扰 prefs = { "download.default_directory": target_path, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": True } chromeOptions.add_experimental_option("prefs", prefs) # 修正参数名,新旧版本Selenium都兼容这个写法 driver = webdriver.Chrome(executable_path=r"D:\ChromeDriverExtracted\chromedriver", options=chromeOptions) driver.get("http://demo.automationtesting.in/FileDownload.html") driver.maximize_window() # 下载txt文件逻辑 driver.find_element_by_id("textbox").send_keys("testing") driver.find_element_by_id("createTxt").click() driver.find_element_by_id("link-to-download").click() # 下载pdf文件逻辑 driver.find_element_by_id("pdfbox").send_keys("testing download text file") driver.find_element_by_id("createPdf").click() driver.find_element_by_id("pdf-link-to-download").click() time.sleep(3) # 延长等待时间避免文件未下载完成就关闭浏览器 driver.close()
额外注意事项
- 如果你的Chrome浏览器版本高于115,建议使用Chrome官方的驱动管理工具自动匹配驱动版本,避免驱动和浏览器版本不兼容导致配置失效
- 检查目标文件夹的读写权限,确保Chrome有权限写入文件到该路径
内容的提问来源于stack exchange,提问作者NikaTheKilla
相关产品推荐
相关产品推荐

