How do I automatically download files from a pop up dialog using selenium-python?

SeleniumAutomation TestingTesting Tools

We can automatically download files from a pop up dialog using Selenium webdriver with Python. After clicking the download link, a dialog box appears for the user to select various options to Save the file.

We have to programmatically configure the path where the download has to be performed such that every time the Firefox browser is launched, the Firefox profile is proper to perform the download at the desired location.

Open the address bar of Firefox, and enter about:config and press Enter . All the browser preferences shall be available with Edit and Toggle buttons. We shall use the Firefox Options class to set the download preferences for the browser.

Example

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
#object of Options class
op = Options()
#save file to path defined for recent download with value 2
op.set_preference("browser.download.folderList",2)
#disable display Download Manager window with false value
op.set_preference("browser.download.manager.showWhenStarting", False)
#download location
op.set_preference
("browser.download.dir","C:\\Users\\ghs6kor\\Documents\\Download")
#MIME set to save file to disk without asking file type to used to open file
op.set_preference
("browser.helperApps.neverAsk.saveToDisk",
"application/octet-stream,application/vnd.ms-excel")
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe",
firefox_options=op)
driver.maximize_window()
#launch URL
driver.get("https://the-internet.herokuapp.com/download");
#click download link
l = driver.find_element_by_link_text("xls-sample1.xls")
l.click()

Output

The file downloaded at the declared location.

raja
Published on 01-Feb-2021 11:47:42
Advertisements