Download file with Selenium Chromedriver in headless mode

Asked

Viewed 520 times

3

I am trying to download a file in headless mode.

I installed 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 does not download (if I do in normal mode does in folder I step).

Someone who has done it in c#?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.