Emerson Cod
Emerson Cod

Reputation: 2090

How to download a file with Selenium and ChromeDriver

I have a website to test with selenium and ChromeDriver (on windows), where I like to test the functionality to export data and import it again.

The export creates a xml file that is downloaded on ones computer. When running this with webdriver, Chrome asks me whether to keep the file or discard it, as it might be a potential threat.

How can I switch off this behavior inside my test ? Is there a chrome setting I can use, so that a file is no matter what downloaded ?

Thanks

Upvotes: 0

Views: 5900

Answers (2)

Hari kishen
Hari kishen

Reputation: 463

The below Program will help you to download the files in Chrome with Desired-Capabilities. It is a rich class having lot of utilities, you can go through it in your free time.

public class DownloadChromeFile {
       public static void main(String[] args) {
       System.setProperty("webdriver.chrome.driver","./chromedriver.exe");
       String downloadFilepath = "c:\\download";

       HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
       chromePrefs.put("profile.default_content_settings.popups", 0);
       chromePrefs.put("download.default_directory", downloadFilepath);
       ChromeOptions options = new ChromeOptions();
       HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
       options.setExperimentalOption("prefs", chromePrefs);
       options.addArguments("--test-type");
       options.addArguments("--disable-extensions"); //to disable browser extension popup

       DesiredCapabilities cap = DesiredCapabilities.chrome();
       cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
       cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); // Bydefault it will accepts all popups.
       cap.setCapability(ChromeOptions.CAPABILITY, options);
       driver = new ChromeDriver(cap);  
                driver.get("Your Application Url");
                driver.findElement(By.xpath("Export Button xpath")).click();
        }
} 

Upvotes: 1

Hiten
Hiten

Reputation: 877

Try this. Executed on windows

(How to control the download of files with Selenium Python bindings in Chrome)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Users\xxx\downloads\Test",
  "download.prompt_for_download": False,
  "download.directory_upgrade": True,
  "safebrowsing.enabled": True
})

Upvotes: 2

Related Questions