【问题标题】:Selenium node JavaScript disable downloadsSelenium 节点 JavaScript 禁用下载
【发布时间】:2026-01-28 17:25:02
【问题描述】:

嗨,我在 node 中的 selenium chromedriver 会自动下载文件。 我想禁用自动下载,

因此,我发现了许多 python 线程,并提供了将 download_restrictions 设置为 3 的解决方案,但我猜在 JS 中没有实验性设置,并且 userPreferences 似乎是错误的地方。

有人知道如何在节点中的无头 chrome 中禁用自动下载。

来源: Disable all downloads with ChromeDriver and Selenium

https://chromeenterprise.google/policies/?policy=DownloadRestrictions https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup

我的示例代码,下载目录似乎可以工作

import { Builder, Capabilities } from 'selenium-webdriver';
import * as Chrome from 'selenium-webdriver/chrome.js'

export async function getDriver() {
  const service = new Chrome.ServiceBuilder("./selenium/chromedriver");
  const chromeOpts = await new Chrome.Options()
      .addArguments("--disable-infobars")
      .addArguments("--headless")
      .setUserPreferences({
        "download_restrictions" : 3
      })

  const driver = new Builder()
      .withCapabilities(Capabilities.chrome())
      .setChromeService(service)
      .setChromeOptions(chromeOpts)
      .build();

  return driver;
}

const driver = await getDriver()
driver.get("http://www.africau.edu/images/default/sample.pdf")

【问题讨论】:

    标签: selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    根据 selenium webdriver js 的文档找到 here

    为 Chrome 的用户配置文件设置用户首选项。有关示例,请参见 Chrome 用户数据目录中的“首选项”文件。

    如果我们必须阻止所有下载,那么请使用上面共享的 python 示例。您需要如下设置 chrome 选项:

    const chromeOpts = await new Chrome.Options()
          .addArguments("--disable-infobars")
          .setUserPreferences({
            "download_restrictions" : 3
          })
    

    我为我的案例尝试了这个,我发现这个配置是有效的。以下是我在测试执行期间发现的日志:

    Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
    ChromeDriver was started successfully.
    [1615982301.751][INFO]: [0ecc2308b910c768a3c91d84cdacbdd8] COMMAND InitSession {
       "capabilities": {
          "alwaysMatch": {
             "browserName": "chrome",
             "goog:chromeOptions": {
                "args": [ "--disable-infobars" ],
                "prefs": {
                   "download_restrictions": 3
                }
             }
          }
       },
       "desiredCapabilities": {
          "browserName": "chrome",
          "goog:chromeOptions": {
             "args": [ "--disable-infobars" ],
             "prefs": {
                "download_restrictions": 3
             }
          }
       }
    }
    

    下面是响应的 sn-p,我可以看到偏好得到反映:

       "dns_prefetching": {
          "enabled": false
       },
       "download_restrictions": 3,
    
    

    【讨论】:

    • 您好,感谢您的帮助,不幸的是它不起作用,我在上面的主帖中添加了一个完整的代码来测试。 TestSystem 是 Ubuntu 20.04 ,也许它在其他机器上有其他行为?重要的是无头。
    【解决方案2】:

    找到我自己的肮脏技巧,不是一个好的解决方案,但它有效

    { "download.default_directory": "/dev/null", "download_restrictions": 3 }
    

    【讨论】: