How can I download a file on a click event using selenium?

SeleniumAutomation TestingTesting Tools

We can download a file on a click event in Selenium. Normally, on clicking on the download link, a pop-up comes with the file name along with the Open and Save option.

To download with a click event, an object of the FirefoxOptions class is to be created. Then with the addPreference method, we shall configure browser preferences.

We shall mention the location where the download is to be done along with the neverAsk.openFile and neverAsk.saveToDisk preferences are to be set.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class FileDwnloadWithClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      // create object of FirefoxOptions class
      FirefoxOptions profile = new FirefoxOptions();
      // adding browser preferences with addPreference method
      profile.addPreference("", 2);
      // location of downloaded file
      profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x msexcel,application/excel," + "application/x-excel,application/," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml");
      profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/ excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml");
      // connecting browser options to webdriver
      WebDriver driver = new FirefoxDriver(profile);
      //maximize window
      // identify element and start download


Moreover, file gets downloaded at the mentioned location.

Published on 28-Dec-2020 17:24:26