How to download a file using Selenium and Python
Related Product On This Page Download files to a specific folder in Ch
Related Product
- Download files to a specific folder in Chrome browser using Selenium
- Download files to a Specific folder in Firefox browser utilize Selenium
- How to verify if the file was successfully download?
- How to discover the MIME type to delimitate when downloading files with Selenium WebDriver in Firefox
- Handling Common File Types
- Best Practices for Downloading Files with Selenium in Python
How to download a file use Selenium and Python
Selenium examine often regard download files like reports or revenue. Since WebDriver can & # 8217; t handle download prompt, set browser preferences to salve files automatically. With Java/Python and creature like BrowserStack, you can efficiently automate and validate file downloads during functional and regression testing.
Overview
How to download files to a Specific folder using Selenium
- Step 1:Import necessitate packages
- Step 2:Set Browser option
- Step 3:Create a script to sail to the site and click on download
- Step 4:Run the trial
- Step 5: Validate the downloaded file
Handling Common File Types
- Disable the built-in viewer using browser settings to download PDF files.
- The Apache POI library can be used to handle Excel files.
- Use of the ZIP module to unzip and control a ZIP file.
- Take the supporter of appropriate libraries (in Java or Python) to handle CSV files.
Best Practices for Downloading Files with Selenium in Python
- Use a freestanding download folder and blue-pencil the file after each test run.
- Disable the auto-download file prompting in the browser and validate the file eccentric and contents after download.
- Make use of dynamic waits in place of traditional sleep delay.
This guide explicate how to download file in Selenium, handling common file types, best practices to postdate and more.
Download file to a specific folder in Chrome browser apply Selenium
Prerequisites:
- Users need to have a basic setup of in their system.
Now, let ’ s discuss how todownload a file using Selenium and Python.
The challenge here is that the downloading summons or approach is different in different browsers & # 8211; such as Firefox and Chrome. So if a tester is using to download file they take to have separate configurations for each browser.
This guide will explain two coming. With it, testers can use Selenium to download files to specific folders in both Chrome and Firebox.
Read More:
Step 1: Import required packages to Python exam script
from selenium import webdriver significance time
The code snippet above imports two packages:
- webdriver:Helps to do browser-specific actions such as pilotage, click, etc.
- time:Helps to pause the script at a coveted time.
Step 2: Set Chrome options
option = webdriver.ChromeOptions (); prefs = {`` download.default_directory '': '' & lt; directory_path & gt;; # example: prefs = {`` download.default_directory '': '' C: \Tutorial\down ''}; options.add_experimental_option (`` prefs '', prefs);Explanation of the code:
- options:Helps set the preferences to Chrome browser.
- download.default_directory:Used for alter the default download directory.Example: The code specifies C: \Tutorial\down, which means that the file will be downloaded to that locating.
- add_experimental_option:Allows users to add these preferences to their Selenium webdriver object.
Step 3: Create chrome driver object with options
driver = webdriver.Chrome (executable_path='./chromedriver ', chrome_options=options);
Explanation of the codification:
- driver:Creates with above mentioned alternative.
Note: executable_path should be the proportional path where the chromedriver is situate. In this case, it is the root folder so it is mentioned as./chromedriver
Step 4: Create a script to voyage to the website and click on download .csv
The steps above have set the preferences and imported all take parcel. Adjacent, the tester must write the script to navigate the website and click on thedownload file option.
from selenium import webdriver importation time try: driver.get ('https: //www.browserstack.com/test-on-the-right-mobile-devices '); gotit= driver.find_element_by_id ('accept-cookie-notification '); gotit.click (); downloadcsv= driver.find_element_by_css_selector ('.icon-csv '); downloadcsv.click (); time.sleep (5) driver.close () except: mark (`` Invalid URL '')Explanation of the code:
- driver.get:Navigates to the URL where the relevant file is located
As shortly as Selenium sail to the, they ask to accept the cooky, which must be done first to download the file.
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
- gotit.click ():detent to accept cookie.
- downloadcsv:variable holds the locator for .csv file.
- downloadcsv.click ():On execute this action, Selenium downloads the file to the specific folder mentioned in Step 2.
Step 5: Run the test
When put together from footstep 1 to step 4, the code looks as below. On executing this script, the tester should be able to automate file download utilize Selenium and Python.
from selenium import webdriver signification time options = webdriver.ChromeOptions (); prefs = {`` download.default_directory '': '' C: \Tutorial\down ''}; options.add_experimental_option (`` prefs '', prefs); driver = webdriver.Chrome (executable_path='./chromedriver ', chrome_options=options); try: driver.get ('https: //www.browserstack.com/test-on-the-right-mobile-devices '); downloadcsv= driver.find_element_by_css_selector ('.icon-csv '); gotit= driver.find_element_by_id ('accept-cookie-notification '); gotit.click (); downloadcsv.click (); time.sleep (5) driver.close () except: mark (`` Invalid URL '')After executing the book the file will be downloaded to the trust location.
Now you can navigate to the folder mentioned inStep 2, and get the Selenium downloaded file.
Download files to a Specific booklet in Firefox browser utilize Selenium
Step 1: Import the required packages
This step remains the same for both Chrome and Firefox. Import necessitate packages to the test scripts.
from selenium meaning webdriver import clip
Read More:
Step 2: Create Firefox Profile
profile = webdriver.FirefoxProfile () profile.set_preference (`` browser.download.folderList '', 2) profile.set_preference (`` browser.download.manager.showWhenStarting '', False) profile.set_preference (`` browser.download.dir '', '' & lt; path_to_downlaod_directory & gt; '') # Example: profile.set_preference (`` browser.download.dir '', '' C: \Tutorial\down '') profile.set_preference (`` browser.helperApps.neverAsk.saveToDisk '', '' application/octet-stream '')
Explanation of the codification:
- profile:The profile object is specific to FirefoxDriver which holds all the preferences to be set.
- browser.download.folderList: Setting this preference recite to not use the default directory for downloading the file.
- browser.download.manager.showWhenStarting:Setting this preference turn off the showing of download progress.
- browser.download.dir:Setting this preference makes Selenium download the file to a specific folder (ex: C: \Tutorial\down).
- browser.helperApps.neverAsk.saveToDisk: Tells Firefox to automatically download the files of the selected mime-types. In this case, its application/octet-stream.
Note:If testers are timid about how to find the mime type that must be define in orientation, scroll to the section on“How to find the MIME type to specify when downloading files with Selenium WebDriver in Firefox” later in this article.
Step 3: Create Firefox driver objective with all preferences
driver = webdriver.Firefox (firefox_profile=profile, executable_path='.\geckodriver ')
The codification above passes two parameters videlicet:firefox_profile and executable route.
- firefox_profile:Sets the profile defined in the steps above.
- feasible path:This value should point to the binary file, if the binary is located in the root folder.\geckodriver.
Step 4: Write a handwriting to navigate to the webpage and download file
try: driver.get ('https: //www.browserstack.com/test-on-the-right-mobile-devices '); gotit= driver.find_element_by_id ('accept-cookie-notification '); gotit.click (); downloadcsv= driver.find_element_by_css_selector ('.icon-csv '); downloadcsv.click (); time.sleep (5); driver.quit (); except: print (`` Invalid URL '')This code snippet remains the like for both Chrome and Firefox.
Step 5: Execute the playscript
When put together from step 1 to tread 3, the code looks as below. On fulfil this script, the tester should be able to automate file download employ Selenium and Python.
from selenium import webdriver import time profile = webdriver.FirefoxProfile () profile.set_preference (`` browser.download.folderList '', 2) profile.set_preference (`` browser.download.manager.showWhenStarting '', False) profile.set_preference (`` browser.download.dir '', '' & lt; path_to_downlaod_directory & gt; '') # Example: profile.set_preference (`` browser.download.dir '', '' C: \Tutorial\down '') profile.set_preference (`` browser.helperApps.neverAsk.saveToDisk '', '' application/octet-stream '') driver = webdriver.Firefox (firefox_profile=profile, executable_path='.\geckodriver ') try: driver.get ('https: //www.browserstack.com/test-on-the-right-mobile-devices '); gotit= driver.find_element_by_id ('accept-cookie-notification '); gotit.click (); downloadcsv= driver.find_element_by_css_selector ('.icon-csv '); downloadcsv.click (); time.sleep (5) driver.quit (); except: print (`` Invalid URL '')After execution of the script, Firefox downloads the file:
Navigate to the directory specified in Step 2 to get the Selenium downloaded file.
How to verify if the file was successfully downloaded?
To confirm if a file is downloaded properly, check the presence of the anticipate file in the mark directory. Since Selenium can not directly confirm the downloads, validation can be done by control the expected file gens, propagation, or size after the download is completed.
In Python:
import os spell time def is_file_downloaded (download_dir, file_name, timeout=10): file_path = os.path.join (download_dir, file_name) for _ in range (timeout): if os.path.exists (file_path): return True time.sleep (1) return False download_dir = `` /path/to/downloads '' file_name = `` example.csv '' if is_file_downloaded (download_dir, file_name): mark (`` File download successfully. '') else: print (`` File not found. '')
In Java:
importjava.io.File;public classVerifyDownload {public static booleanisFileDownloaded (String downloadDir, String fileName,inttimeoutInSeconds)throwsInterruptedException {File dir =newFile (downloadDir); File [] dirContents;for (inti = 0; i & lt; timeoutInSeconds; i++) {dirContents = dir.listFiles ();if(dirContents! =null) {
for(File file: dirContents) {if(file.getName () .equals (fileName)) {return true;}}} Thread.sleep (1000);}return false;
}
public static voidmain (String [] args)throwsInterruptedException {String path = `` C: \\Users\\YourName\\Downloads ''; String expectedFile = `` example.csv '';if(isFileDownloaded (path, expectedFile, 10)) {System.out.println (`` File downloaded successfully. ``);}else{System.out.println (`` File not found. ``);}}}How to find the MIME type to specify when downloading files with Selenium WebDriver in Firefox
In the Firefox penchant, one has to specify the MIME type. However, most multiplication, the tester is not sure which MIME type to specify. Fortunately, there is a solution.
Let ’ s regard the instance render above. In order to find the MIME type, do the following:
1. Exposed Firefox browser. Navigate to URL
2. Navigate to the .CSV download button and copy the download link
3. Open a new browser window. Then open the network tab:
4. Paste the URL replicate and look for the network tab request:
Here in the request, look for the initiatory request. Therein, find the content-type. Mention it in Firefox preferences when writing the test script for download a file using Selenium.
Handling Common File Types
Selenium can initiate downloads of different types of files, but handling these files is dependent on the browser scene.
- PDF: Common browsers such as and have built-in PDF viewers. Hence, rather than download, a tie to a PDF will open in a new window. Therefore, disable the in-built viewer using browser settings and set the browser to auto-download instead of in-browser preview.
- Excel Files (XLS, XLSX): Excel files usually download normally, but sometimes browser will prompt users or reject to notice the file type. Make sure your test environs is sending correct MIME coping and set the browser to block download prompts. Apache POI library can be used to handle excel file.
- ZIP Files:ZIP archive are the simplest. No exceptional browser configuration is normally required. Make use of the Zip faculty to unzip and control its substance.
- CSV: CSV files are often not downloaded properly and open as plain texts. These files can be handled with the assistant of appropriate libraries such as csv (Python) and openCSV (Java).
Good Practices for Downloading Files with Selenium in Python
In order to supply dependability and consistency in your automated tests, it is crucial to properly configure the browser, handle file check, and stick up to the clean-up recitation. Given below are the good practices to be followed when download files in Selenium:
- Use a freestanding download brochurefor each test run.
- Disable theauto-download fileprompts in the browser.
- Make use ofdynamic waitsin property of traditional sleep waits.
- Clean the download pamphletafter each exam toprevent mistaken positives.
- Prefer headless modeonly when the download support is set up completely.
- Validate the downloaded substancefor formatting, size, or value.
Conclusion
Bear in mind tests must be action on existent devices and browsers. Remember that is a major care for every developer and examiner. Every website has to work seamlessly on multiple device-browser-OS combination. With distinct devices being expend to admission the internet globally, all software has to be optimize for different configurations, viewports, and screen firmness.
In this state, no aper or simulator can double. Software needs to be tested on real devices so that they can work in real-world circumstances such as a low battery, incoming Call, weak meshing posture, and so on. If an in-house lab is not accessible, opt for a that offers existent devices.
BrowserStack ’ s offers 3500+ real devices and browser for machine-controlled testing. That means user can run tests on multiple real devices and browsers by just signing up, lumber in, and select the required combinations. Testers can also acquit on 30+ real browser versions across Windows and macOS. Detects bugs before exploiter do by testing software in real user weather with BrowserStack.
On This Page
- Download file to a specific brochure in Chrome browser apply Selenium
- Download files to a Specific folder in Firefox browser use Selenium
- How to verify if the file was successfully downloaded?
- How to find the MIME type to specify when download files with Selenium WebDriver in Firefox
- Handling Common File Types
- Better Practices for Downloading Files with Selenium in Python
# Ask-and-Contributeabout this subject with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free