Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading file to specified location with Selenium and python

Ok so far i have my programing going to the website i want to download link from and selecting it, then the firefox dialogue box shows up and i don't know what to do. i want to save this file to a folder on my desktop. I am using this for a nightly build so i need this to work. Please help.

Here is my code that grabs the download link from the website:

driver = web driver.Firefox()
driver.implicitly_wait(5)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]".click()
like image 355
Jerad Bill Avatar asked Aug 11 '14 20:08

Jerad Bill


People also ask

Can Selenium download files?

If you are an automation tester fixated on Selenium automation testing, the chances are that you might run into a requirement of testing a feature around downloading files. While being a powerful tool for performing automated browser testing, Selenium natively doesn't support download functionality.


2 Answers

You need to make Firefox save this particular file type automatically.

This can be achieved by setting browser.helperApps.neverAsk.saveToDisk preference:

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", 'PATH TO DESKTOP')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")

driver = webdriver.Firefox(firefox_profile=profile)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]").click()

More explanation:

  • browser.download.folderList tells it not to use default Downloads directory
  • browser.download.manager.showWhenStarting turns of showing download progress
  • browser.download.dir sets the directory for downloads
  • browser.helperApps.neverAsk.saveToDisk tells Firefox to automatically download the files of the selected mime-types

You can view all these preferences at about:config in the browser. There is also a very detailed documentation page available here: About:config entries.

Besides, instead of using xpath approach, I would use find_element_by_partial_link_text():

driver.find_element_by_partial_link_text("DEV.tgz").click()

Also see:

  • Access to file download dialog in Firefox
  • Firefox + Selenium WebDriver and download a csv file automatically
like image 198
alecxe Avatar answered Oct 21 '22 03:10

alecxe


If the application is generated dynamically (mime-types) using Chrome browser will be a better approach since the Chrome will not open the file download pop-up.But multiple download option should be enabled if you need multiple downloads.

like image 22
Ravinath Edirisinghe Avatar answered Oct 21 '22 04:10

Ravinath Edirisinghe