我正在使用第77版chrome测试一些下载。但是我不明白为什么它不允许在无头模式下下载文件(仅在无头模式下发生)。这是我正在使用的代码。
_chromeOptions.AddUserProfilePreference(“ download.default_directory”,@“目录文件夹”); _chromeOptions.AddUserProfilePreference(“ intl.accept_languages”,“ nl”); _chromeOptions.AddUserProfilePreference(“ disable-popup-blocking”,“ true”); _webdriver =新的ChromeDriver(_chromeOptions);
答案 0 :(得分:0)
或者,您可以使用Firefox无头浏览器下载文件。
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);
答案 1 :(得分:0)
默认情况下,Chrome无头模式禁用文件下载。参见:https://bugs.chromium.org/p/chromium/issues/detail?id=696481
您需要对驱动程序进行API调用才能启用它。
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));
答案 2 :(得分:0)
此函数返回自动下载设置为“USERPROFILE”下载文件夹的无头 Chrome 浏览器实例。您可以对所需的下载文件夹进行硬编码。
从测试初始化程序调用函数 GetBrowserWebDriver("Chrome")
public IWebDriver GetBrowserWebDriver(string browser)
{
IWebDriver currentDriver = null;
switch (browser)
{
case "Chrome":
var options = new ChromeOptions();
options.AddArgument("headless");
string downloadPath = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\Downloads";
options.AddUserProfilePreference("download.default_directory", downloadPath);
options.AddUserProfilePreference("profile.default_content_setting_values.automatic_downloads", 1);
options.AddArgument("--window-size=1920,1080");
currentDriver = new ChromeDriver(options);
break;
case "Firefox":
currentDriver = new FirefoxDriver();
break;
case "IE":
currentDriver = new InternetExplorerDriver(new InternetExplorerOptions() { IgnoreZoomLevel = true });
break;
default:
throw new NotSupportedException("");
}
return currentDriver;
}
答案 3 :(得分:0)
我能够使用以下 ChromeOptions 以无头模式下载文件:
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--headless");
chromeOptions.AddArgument("--disable-gpu");
chromeOptions.AddUserProfilePreference("download.default_directory", ApplicationSettings.StagingDirectory);
chromeOptions.AddUserProfilePreference("profile.default_content_setting_values.automatic_downloads", 1);
driver = new ChromeDriver(chromeOptions);
Chrome 版本 - 89.0.4389
Chrome 驱动程序版本 - 89.0.4389.2300