问题
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