Selenium download file automatically c#

感情迁移 提交于 2019-12-04 04:32:08

问题


I'm try to setup Firefox in order to be auto-download files. I did how suggested in enter link description here, But I cannot get it to work.

This is my code:

FirefoxOptions options = new FirefoxOptions();
        options.SetPreference("browser.download.folderList", 2);
        options.SetPreference("browser.download.dir", "C:\\Windows\\temp");
        options.SetPreference("browser.download.useDownloadDir", true);
        options.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
        options.SetPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer
        options.SetPreference("browser.download.useDownloadDir", true);
        driver = new FirefoxDriver(options);
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://www.mozilla.org/en-US/foundation/documents");
        driver.FindElement(By.LinkText("IRS Form 872-C")).Click();

The PDF is still opened in the browser PDF viewer. Any idea?


回答1:


To disable open and download pdf in firefox:

FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.download.folderList", 2);
options.addPreference("browser.download.dir", downloadPath);
options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
options.addPreference("pdfjs.enabledCache.state",false); 
WebDriver driver = new FirefoxDriver(options);

List of Mime Tipes can be found here.




回答2:


My mistake, I didn't realize that the question was for C #.

So I did it in Java, I suppose selenium functionalities are very similar regardless of language. However, the important thing here is how to configure FirefoxDriver.

Using selenium 3.8:

    FirefoxProfile profile = new FirefoxProfile();
    //if you want to download the file to a different directory than the default
    profile.setPreference("browser.download.dir", "dirPath");

    //0: the desktop, 1 (default): the downloads folder, 2: the last folder specified for a download
    profile.setPreference("browser.download.folderList", 2);

    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf;");
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("pdfjs.disabled", true);

    //The previous configuration can also be done in FirefoxOptions, I did not know and I simply passed the FirefoxProfile object
    FirefoxOptions fo = new FirefoxOptions();
    fo.setProfile(profile);

    FirefoxDriver driver = new FirefoxDriver(fo);

    driver.get("http://your.web");
    driver.findElement(By.id("download_button")).click();


来源:https://stackoverflow.com/questions/51949871/selenium-download-file-automatically-c-sharp

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