Selenium C# - Chrome Driver doesn't download files on headless mode

て烟熏妆下的殇ゞ 提交于 2019-12-08 13:52:41

问题


I'm using the 77th version of chrome to test some downloads. But I don't understand why it doesn't let download files on headless mode (Only happens on headless mode). This is the code I'm using.

_chromeOptions.AddUserProfilePreference("download.default_directory", @"Directory Folder"); _chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl"); _chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true"); _webdriver = new ChromeDriver(_chromeOptions);


回答1:


As alternative, you can download files using Firefox headless browser.

FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", "C:\\Windows\\temp");
profile.setPreference( "browser.download.manager.showWhenStarting", false );
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
options.setProfile(profile);
driver = new FirefoxDriver(options);



回答2:


Downloading of files is disabled in Chrome Headless mode by default. See: https://bugs.chromium.org/p/chromium/issues/detail?id=696481

You need to make an API call to the driver to enable it.

var driver = new ChromeDriver(driverService, options);
// Allow download in headless mode
var param = new Dictionary<string, string> {{"behavior", "allow"}, {"downloadPath", DownloadPath}
};
var cmdParam = new Dictionary<string, object> {{"cmd", "Page.setDownloadBehavior"}, {"params", param}};
var url = driverService.ServiceUrl + "session/" + driver.SessionId + "/chromium/send_command";
var cli = new WebClient {Headers = {[HttpRequestHeader.ContentType] = "application/json"}};
_ = cli.UploadString(url, JsonConvert.SerializeObject(cmdParam));


来源:https://stackoverflow.com/questions/58270951/selenium-c-sharp-chrome-driver-doesnt-download-files-on-headless-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!