Monday, 4 July 2016

How to auto download a file in Selenium

When you try to download a file from a website in Selenium, window dialog may appear. But Selenium can not handle such native windows. We may use AUTOIT scripts for handling native windows. But that's only possible on Windows OS.

Better solution is to change the driver settings so that file is automatically downloaded to system bypassing the File save dialog.

If you are using Firefox, you can use below code to start the driver with below profile.

FirefoxProfile myprofile= new FirefoxProfile();
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "c:\\mydownloadlocation\\xyz");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
WebDriver driver = new FirefoxDriver(myprofile);

If you are using Chrome driver, you can use below code to skip the download window.

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.prompt_for_download", false);
        prefs.put("download.default_directory", "path-to-download-directory");
        options.setExperimentalOption("prefs", prefs);
        WebDriver driver = new ChromeDriver(options);

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

1 comment:

Buy Best Selenium Books