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

Posted on

Question :

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

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()


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?

Asked By: sam


Answer #1:

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('', 2) # custom location
profile.set_preference('', False)
profile.set_preference('', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

browser = webdriver.Firefox(profile)


Added profile manipulation code to prevent download dialog.

Answered By: falsetru

Answer #2:

I’ll admit this solution is a little more “hacky” than the Firefox Profile saveToDisk alternative, but it works across both Chrome and Firefox, and doesn’t rely on a browser-specific feature which could change at any time. And if nothing else, maybe this will give someone a little different perspective on how to solve future challenges.

Prerequisites: Ensure you have selenium and pyvirtualdisplay installed…

  • Python 2: sudo pip install selenium pyvirtualdisplay
  • Python 3: sudo pip3 install selenium pyvirtualdisplay

The Magic

import pyvirtualdisplay
import selenium
import selenium.webdriver
import time
import base64
import json

root_url = ''
download_url = ''

print('Opening virtual display')
display = pyvirtualdisplay.Display(visible=0, size=(1280, 1024,))

print('Opening web browser')
driver = selenium.webdriver.Firefox()
#driver = selenium.webdriver.Chrome() # Alternately, give Chrome a try

print('Retrieving initial web page')

print('Injecting retrieval code into web page')
    window.file_contents = null;
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function() {
            window.file_contents = reader.result;
    };'GET', %(download_url)s);
""".replace('rn', ' ').replace('r', ' ').replace('n', ' ') % {
    'download_url': json.dumps(download_url),

print('Looping until file is retrieved')
downloaded_file = None
while downloaded_file is None:
    # Returns the file retrieved base64 encoded (perfect for downloading binary)
    downloaded_file = driver.execute_script('return (window.file_contents !== null ? window.file_contents.split(',')[1] : null);')
    if not downloaded_file:
        print('tNot downloaded, waiting...')

print('Writing file to disk')
fp = open('google-logo.png', 'wb')
driver.close() # close web browser, or it'll persist after python exits.
display.popen.kill() # close virtual display, or it'll persist after python exits.


We first load a URL on the domain we’re targeting a file download from. This allows us to perform an AJAX request on that domain, without running into cross site scripting issues.

Next, we’re injecting some javascript into the DOM which fires off an AJAX request. Once the AJAX request returns a response, we take the response and load it into a FileReader object. From there we can extract the base64 encoded content of the file by calling readAsDataUrl(). We’re then taking the base64 encoded content and appending it to window, a gobally accessible variable.

Finally, because the AJAX request is asynchronous, we enter a Python while loop waiting for the content to be appended to the window. Once it’s appended, we decode the base64 content retrieved from the window and save it to a file.

This solution should work across all modern browsers supported by Selenium, and works whether text or binary, and across all mime types.

Alternate Approach

While I haven’t tested this, Selenium does afford you the ability to wait until an element is present in the DOM. Rather than looping until a globally accessible variable is populated, you could create an element with a particular ID in the DOM and use the binding of that element as the trigger to retrieve the downloaded file.

Answered By: Joshua Burns

Answer #3:

In chrome what I do is downloading the files by clicking on the links, then I open chrome://downloads page and then retrieve the downloaded files list from shadow DOM like this:

docs = document

This solution is restrained to chrome, the data also contains information like file path and download date. (note this code is from JS, may not be the correct python syntax)

Answered By: TiagoLr

Answer #4:

Here is the full working code. You can use web scraping to enter the username password and other field. For getting the field names appearing on the webpage, use inspect element. Element name(Username,Password or Click Button) can be entered through class or name.

from selenium import webdriver
# Using Chrome to access web
options = webdriver.ChromeOptions() 
options.add_argument("download.default_directory=C:/Test") # Set the download Path
driver = webdriver.Chrome(options=options)
# Open the website
    driver.get('xxxx') # Your Website Address
    password_box = driver.find_element_by_name('password')
    password_box.send_keys('xxxx') #Password
    download_button = driver.find_element_by_class_name('link_w_pass')
    print("Faulty URL")
Answered By: Ashutosh Kumar

Leave a Reply

Your email address will not be published.