How can I download a file on a click event using selenium?

sam picture sam · Aug 26, 2013 · Viewed 85k times · Source

I am working on python and selenium. I want to download file from clicking event using selenium. I wrote following code.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")

browser.close()

I want to download both files from links with name "Export Data" from given url. How can I achieve it as it works with click event only?

Answer

falsetru picture falsetru · Aug 26, 2013

Find the link using find_element(s)_by_*, then call click method.

from selenium import webdriver

# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

browser = webdriver.Firefox(profile)
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")

browser.find_element_by_id('exportpt').click()
browser.find_element_by_id('exporthlgt').click()

Added profile manipulation code to prevent download dialog.