Download files using Selenium webdriver
To begin with, we all download a lot of files from the browser especially, for instance songs, bills, reports, photographs, and videos vis a vis day to day life. Above all, point often overlooked is file download is one of the most important and frequent activities done by every web user. Without doubt, being a developer/Automation Engineer we have to develop this feature or automate this activity. To clarify, Selenium WebDriver and Javascript executor provides flexibility to download files, get the filename and set download folder path. You can download files using selenium webdriver.
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. In general, as a matter of fact, on the positive side, to perform these activities we will use Selenium WebDriver and Javascript Executor. Without delay, go through this tutorial.
All in all, in due time, refer below for step by step guide, detailed explanation, snapshots, and complete code.
Pre Requisite:
- Selenium Project should be set up on your machine. (If Selenium Project is not set up then refer our blog-
Refer another key point – 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: As soon as method is created, 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: For the most part, to customize Chrome properties, use ChromeOptions. Make object of ChromeOptions, which is equally important.
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);
Embody ChromeDriver with above ChromeOptions object.
WebDriver driver = new ChromeDriver(options);
On the other hand, 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();
In effect, 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");
- Step 6: Additionally, take into account Javascript Executor and Jquery to get download percentage.
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:
Overall use Javascript Query to get downloaded file name.
document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').text
On the condition that, below JQuery to get download link
document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('div#content #file-link').href
Get download 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: Summing up, 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. To this end, on account of selenium learning feel free to message us on Facebook/WhatsApp if you face any issue.