Download Files using Selenium WebDriver

We all download a lot of files from the browser like songs, bills, reports, photographs, and videos in day to day life. File download is one of the frequent activities done by every web user. No doubt, being a developer/Automation Engineer we have to develop this feature or automate this activity. Selenium WebDriver and Javascript executor provides flexibility to download files, get the filename and set download folder path.

Welcome to Selenium tutorial, in this tutorial we will learn everything about file downloading on the browser. First, we will set the download folder path, download files in a browser, check download progress, file download link, downloaded folder path, and downloaded file name. To perform these activities we will use Selenium WebDriver and Javascript Executor.

Refer below for step by step guide, detailed explanation, snapshots, and complete code.

Pre Requisite:

  1. Selenium Project should be set up on your machine. (If Selenium Project is not set up then refer our blog-

Refer – Selenium Installation Tutorial With Example

Download Files in Selenium:

  • Step 1:  Open Selenium project and create one test Class ie downloadFile.java
  • Step 2: Create a method to write file download code ie. TestDownloadFile
  • Step  3:  Set browser binaries path or use WebDriver
ManagerWebDriverManager.chromedriver().version("83.0.4103.61").setup();
 Or,
// return driver folder path
String driverpath = path + "\\driverfolder\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver",driverpath );
  • Step 4: To customize Chrome properties, use ChromeOptions. Make object of ChromeOptions.
ChromeOptions options = new ChromeOptions();
  • Step 5: Set ChromePref and pass the download folder path with key “download.default_directory”.  After this pass setExperimentalOption in Chrome options. (Check our Chrome Options tutorial)
Map<String, String> chromePref = new HashMap<String, String>();
String downloadFolder = "C:\\Users\\user\\Desktop\\songs";
chromePref.put("download.default_directory", downloadFolder);
options.setExperimentalOption("prefs", chromePref);
  • Step 6: Instantiate ChromeDriver with above ChromeOptions object.
WebDriver driver = new ChromeDriver(options);
  • Step 7: Navigate to download page and click on link to download file.
driver.get("https://songspk3.online/dream-girl-songs.html");
//Click now download Link
driver.findElement(By.xpath("//table[1]//tbody[1]//tr[1]//td[2]//a[1]//strong[1]")).click();
  • Step 8: Use Java script executor to open a new tab in the same browser, switch to a new window (Refer our tutorial on: Multiple window handling for more details), and navigate to chrome download path.
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeScript("window.open()");
Set<String> allWinowHandles= driver.getWindowHandles();
// Switch to new Window Handle
 for(String winHandle: allWinowHandles){
     //Switch to second window
     if(!winHandle.equals(parentWindow)){
         driver.switchTo().window(winHandle);
     }
 }
 // navigate to chrome downloads
 driver.get("chrome://downloads");
Download In Progress
  • Step 9: Use Javascript Executor and Jquery to get download percentage.
Jquery to verify downloaded file
JavascriptExecutor downloadWindowExecutor = (JavascriptExecutor)driver;
// Wait for Download till 100% completion
double percentageProgress = (double) 0;
while (percentageProgress != 100) {
    percentageProgress = (Long) downloadWindowExecutor.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value");
    System.out.println("Completed Percentage" + percentageProgress);
   Thread.sleep(100);
}

Steps to Verify Downloaded file in Selenium:

  • Step 10 : Use Javascript Query to get downloaded file name.
document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text
JQuery to get Downloaded File name
  • Step 11: Use below JQuery to get download link
document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href
JQuery to get Downloaded file path
  • Step 12: Use below query to get downloaded folder location
document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div.is-active.focus-row-active #file-icon-wrapper src img')

Step 13: Close all browser and Tab: quit() method close the tabs and browser instances.

driver.quit();

Selenium Script for Downloading Files:

Complete Code:

package stepDef;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class downloadFile {
    @Test
    public void TestDownloadFile() throws InterruptedException {
        WebDriverManager.chromedriver().version("83.0.4103.61").setup();
        ChromeOptions options = new ChromeOptions();
        Map<String, String> chromePref = new HashMap<String, String>();
        String downloadFolder = "C:\\Users\\ajit\\Desktop\\Chinees";
        chromePref.put("download.default_directory", downloadFolder);
        options.setExperimentalOption("prefs", chromePref);
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://songspk3.online/dream-girl-songs.html");
        //Click now download Link
        driver.findElement(By.xpath("//table[1]//tbody[1]//tr[1]//td[2]//a[1]//strong[1]")).click();
        // Get Parent Window Handle
        String parentWindow = driver.getWindowHandle();
        //Open New Tab in Same Browser and go to "chrome://downloads" to check Dowonlaod status
        JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
        jsExecutor.executeScript("window.open()");
        // Get all windowHandles
       Set<String> allWinowHandles= driver.getWindowHandles();
       // Switch to new Window Handle
        for(String winHandle: allWinowHandles){
            //Switch to second window
            if(!winHandle.equals(parentWindow)){
                driver.switchTo().window(winHandle);
            }
        }
        // navigate to chrome downloads
        driver.get("chrome://downloads");
// Use JavaScript Executor to get information about Downloaded File
        JavascriptExecutor downloadWindowExecutor = (JavascriptExecutor)driver;
        // Wait for Download till 100% completion
        double percentageProgress = (double) 0;
        while (percentageProgress != 100) {
            percentageProgress = (Long) downloadWindowExecutor.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value");
            System.out.println("Completed Percentage" + percentageProgress);
           Thread.sleep(100);
        }
        // Get File Name using Java Query
        String fileName = (String) downloadWindowExecutor.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text");
        // Get the URL of Download Source link
        String downloadSourceLink = (String) downloadWindowExecutor.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href");
        // Get download folder location
        String downloadedFolder = (String) downloadWindowExecutor.executeScript("return c");
        System.out.println("Details of Downloaded Files");
        // print the details
        System.out.println("Details of Downloaded Files");
        System.out.println("Downloaded File Name: " + fileName);
        System.out.println("Donwloaded File Location: " + downloadedFolder);
        System.out.println("Download Link : " + downloadSourceLink);
        //Assert.assertEquals(downloadedFolder,downloadFolder, "Verified Download Folder Location");
        driver.quit();
}
   
}

Console Output:

Awesome! Now you have successfully completed the tutorial on file download, file name verification, and download link verification. Feel free to message us on Facebook/WhatsApp if you face any issue.

Subscribe to our Newsletter:

0 0 vote
Article Rating
close

Subscribe to our Newsletter:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open chat
Feel free to contact