如何通过JavaScript修改Selenium Chrome的默认下载目录?
解决Selenium Chrome修改默认下载目录失败的问题
原代码存在的问题
- 路径转义错误:Windows系统下的路径分隔符
\在JavaScript字符串中属于转义字符,直接写C:\Study\Selenium会导致路径解析异常,需转义为\\或者改用正斜杠/。 - 拼写错误:原代码路径里的
Selenuim是笔误,正确应为Selenium。 - API调用方式错误:Selenium的
setUserPreferences方法需一次性传入完整的偏好配置对象,多次调用会覆盖之前的设置,无法同时生效多个偏好项。
修正后的代码示例
const { Builder } = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); async function setupChromeDownloadDir() { const options = new chrome.Options(); // 两种合法路径写法二选一:转义反斜杠 或 使用正斜杠 const downloadDir = 'C:\\Study\\Selenium'; // const downloadDir = 'C:/Study/Selenium'; options.setUserPreferences({ 'download.default_directory': downloadDir, 'download.prompt_for_download': false, 'download.directory_upgrade': true, // 可选:添加安全浏览设置,避免部分下载被浏览器拦截 'safebrowsing.enabled': true }); const driver = await new Builder() .forBrowser('chrome') .setChromeOptions(options) .build(); // 后续业务逻辑... } setupChromeDownloadDir();
额外注意事项
- 确保ChromeDriver版本与本地安装的Chrome浏览器版本完全匹配,版本不匹配可能导致配置无法生效。
- 若针对PDF等特定文件类型的下载仍有问题,可添加
plugins.always_open_pdf_externally: true这类偏好项补充配置。
内容的提问来源于stack exchange,提问作者Meir Benodis
相关产品推荐
相关产品推荐

