如何在 selenium Chrome 功能中设置默认下载目录?

新手上路,请多包涵

请找到以下具有 chrome 功能的代码。实际上浏览器并没有将文件下载到指定路径。

 private static DesiredCapabilities getChromeCapabilities() throws Exception {

    String chromePath = BrowserUtil.class.getResource("/Browserdrivers/chromedriver.exe").getPath();
    System.setProperty("webdriver.chrome.driver", chromePath);
    String downloadFilepath = "C:\\TestDownloads";
    ChromeOptions options = new ChromeOptions();
    HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
    chromePrefs.put("profile.default_content_settings.popups", 0);
    chromePrefs.put("download.default_directory", downloadFilepath);
    options.setExperimentalOption("prefs", chromePrefs);
    options.addArguments("--test-type");
    options.addArguments("start-maximized", "disable-popup-blocking");

    DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();
    setProxy(chromeCapabilities);
    chromeCapabilities.setPlatform(Platform.WINDOWS);
    chromeCapabilities.setCapability("name", MDC.get("testname"));
    chromeCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
    return chromeCapabilities;
}

原文由 vini007 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 974
2 个回答

对于 Chromedriver 尝试:

 String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);

注意:- 使用 File.separator 来处理斜线,它会根据执行代码的操作系统来放置语法。在 Windows 中,您需要使用 \\ 作为路径,而如果您使用的是 linux 或 mac,则使用 //

希望这可以帮助。 :)

原文由 Shubham Jain 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于看到此页面的 Python 用户——这是我在 Python Selenium 中设置下载目录的方式(这只是 Shubham 接受的答案的 Python 版本):

 def newChromeBrowser(headless=True, downloadPath=None):
    """ Helper function that creates a new Selenium browser """
    options = webdriver.ChromeOptions()
    if headless:
        options.add_argument('headless')
    if downloadPath is not None:
        prefs = {}
        os.makedirs(downloadPath)
        prefs["profile.default_content_settings.popups"]=0
        prefs["download.default_directory"]=downloadPath
        options.add_experimental_option("prefs", prefs)
    browser = webdriver.Chrome(options=options, executable_path=CHROMEDRIVER_PATH)
    return browser

原文由 Luke 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题