Selenium4 File Upload and Download

In Selenium, file upload and download are common automation operation requirements.

  • File upload: Throughsend_keys()method to pass the file path to<input type="file">element.

  • File download: By configuring the browser's download options, triggering the download operation, and waiting for the file download to complete.

  • Notes: Ensure the file path is correct, and adjust the wait time and browser configuration according to actual needs.

The following is a detailed description of file upload and download:

File upload

Method Description
send_keys("file_path") Pass the file path to<input type="file">element to implement file upload.
execute_script() If the file upload element is hidden, you can use JavaScript to make it visible.
Third-party tools (such as AutoIT) If file upload is not through<input type="file">implemented, you may need to use third-party tools.

File download

Method Description
Configure browser download options ViaChromeOptionsorFirefoxOptionsset the download path, disable prompts, etc.
click() Click the download button to trigger file download.
Wait for the file download to complete Usetime.sleep()or loop to check whether the file download is complete.
Check downloaded file Useos.listdir()to check files in the download directory.

Common Issues for File Upload and Download

Problem Solution
File upload element is not visible Use JavaScript to make the element visible:driver.execute_script("arguments[0].style.display = 'block';", element)
not<input type="file">element Use third-party tools (such as AutoIT or PyWin32) to simulate the file selection dialog.
Download path configuration failed Ensure the download path exists and is writable, and configure browser options correctly.
File has not finished downloading Increase the waiting time, or use a loop to check whether the file download is complete.

File Upload Operation

File upload is one of the common features in Web applications.

In Selenium, file upload is usually through<input type="file">element.

The following are the steps to implement file upload:

Locate the file upload element: First, we need to locate the input box element for file upload. Usually, this element is a<input>tag with typefile。

Example

file_input = driver.find_element(By.XPATH, "//input[@type='file']")

Send file path: Once the file upload element is located, we can usesend_keys()method to send the absolute path of the file to that element.

Example

file_input.send_keys("/path/to/your/file.txt")

This will trigger the file selection dialog and automatically select the specified file.

Submit the form: In some cases, the form needs to be submitted after file upload. You can do this by clicking the submit button.

Example

submit_button = driver.find_element(By.XPATH, "//input[@type='submit']")
submit_button.click()

Notes

  • Make sure the file path is correct and the file exists.
  • If the file upload element is hidden, you may need to use JavaScript to make it visible.

File Download Operation

File download operations are slightly more complex in Selenium because they involve the browser's download dialog.

The following are the steps to implement file download:

Set download path: First, we need to set the browser's download path. This can be done by setting the browser's preferences.

Example

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
    "download.default_directory": "/path/to/download/directory",
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
})

driver = webdriver.Chrome(options=chrome_options)

This will set the browser's default download path and disable download prompts.

Trigger download: Next, we need to find the link or button that triggers download and click it.

Example

download_link = driver.find_element(By.XPATH, "//a[@id='downloadLink']")
download_link.click()

This will trigger the file download and automatically save it to the download path set earlier.

Wait for download to complete: To ensure the file download is complete, we can usetime.sleep()or a smarter waiting mechanism.

Example

import time
time.sleep(10)  # Wait 10 seconds to ensure the file download is complete

Notes

  • Make sure the download path is writable.
  • If the downloaded file is large, you may need to increase the waiting time.

Handling Download Dialog

In some cases, the browser may pop up a download dialog asking the user whether to save the file. To automate this situation, we can use the following methods:

Use browser preferences: As mentioned above, the download dialog can be disabled by setting the browser's preferences.

Example

chrome_options.add_experimental_option("prefs", {
    "download.prompt_for_download": False
})

Use AutoIT or similar tools: If the download dialog cannot be disabled via browser preferences, you can use tools such as AutoIT to automate handling the dialog.

Example

import autoit

autoit.win_wait_active("File Download")
autoit.control_click("File Download", "Button1")

This will automatically click the "Save" button in the download dialog.

Notes

  • AutoIT scripts need to run in a Windows environment.
  • Make sure the AutoIT script and Selenium script execute synchronously.

Example Code

The following is a complete example showing how to configure Chrome browser download options and download a file:

Example

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
import time
import os

# Set download path
download_dir = "/path/to/download/directory"

# Configure Chrome options
chrome_options = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": download_dir,  # Set download path
    "download.prompt_for_download": False,       # Disable download prompts
    "download.directory_upgrade": True,          # Allow download to the specified directory
    "safebrowsing.enabled": True                 # Enable safe browsing
}
chrome_options.add_experimental_option("prefs", prefs)

# Launch the browser
service = ChromeService(executable_path="/path/to/chromedriver")
driver = webdriver.Chrome(service=service, options=chrome_options)

# Open a web page
driver.get("https://www.example.com/download")

# Click the download button
download_button = driver.find_element(By.ID, "download-button")
download_button.click()

# Wait for the file download to complete
time.sleep(10)  # Adjust the wait time according to file size

# Check whether the file was downloaded successfully
files = os.listdir(download_dir)
print("List of downloaded files:", files)

# Close the browser
driver.quit()
Other Extensions