Download file with Selenium Chromedriver in headless mode

2

I'm trying to download a file in headless mode.

I instantiated the driver like this:

public static IWebDriver CriarWebDriver()
{
    var options = new ChromeOptions();

    if(HelperConfig.GetInstance().Headless)
    {
        options.AddArgument("--headless");
        options.AddArgument("--proxy-server='direct://'");
        options.AddArgument("--proxy-bypass-list=*");
        options.AddArgument("--disable-gpu");
    }
    options.AddArgument("--no-sandbox");
    //options.AddArguments("--incognito");

    var localDownload = HelperConfig.GetInstance().DiretorioDownload;

    //var localDownload = Configuration.ResourcesPath;
    //var localDownload = Assembly.GetExecutingAssembly().Location;
    options.AddArguments("--browser.download.folderList=2");
    options.AddArguments("--browser.helperApps.neverAsk.saveToDisk=image/jpg");
    options.AddArguments("--browser.download.dir=" + localDownload);

    options.AddUserProfilePreference("profile.default_content_settings.popups", 0);
    options.AddUserProfilePreference("download.prompt_for_download", "false");
    options.AddUserProfilePreference("download.default_directory", localDownload);
    options.AddUserProfilePreference("plugins.plugins_disabled", new[] { "Chrome PDF Viewer" });
    //options.AddUserProfilePreference("disable-popup-blocking", "true");

    var driver = new ChromeDriver(options);            
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(HelperConfig.GetInstance().DefaultTimeOutSeconds);
    return driver;
}

And I created this method that I call before the click that generates the download:

protected void HabilitarDownload()
{
    var config = HelperConfig.GetInstance();
    if (config.Headless)
    {
        var param = new Dictionary<string, object>
            {
                { "behavior", "allow" },
                { "downloadPath",HelperConfig.GetInstance().DiretorioDownload }
            };
        var ret = (_driver as ChromeDriver).ExecuteChromeCommandWithResult("Page.setDownloadBehavior", param);
    }

    if (!string.IsNullOrWhiteSpace(config.DiretorioDownload))
        HelperArquivo.CriarDiretorio(config.DiretorioDownload);
}

But in headless mode it does not download (if I do it in normal mode it does in the folder I pass).

Someone who has already done this in C #?

    
asked by anonymous 12.12.2018 / 21:23

0 answers