How can I upload files using Selenium WebDriver?

10    Asked by hashir_8556 in QA Testing , Asked on Jan 15, 2025

I need to automate the process of uploading a file from the local system using Selenium WebDriver. Specifically, I want to perform the following actions:

  1. Click on the "Browse" button to trigger the file upload dialog.

  2. Navigate to the desired location on the local system in the file upload window.

  3. Select the required file.

  4. Click the "Open" button to upload the file.

Answered by Aashna Saito

To upload files using Selenium WebDriver, you can use the send_keys() method to set the file path directly to the file input element. Selenium interacts with the element in the HTML, bypassing the system's file picker dialog.

Here's how you can achieve this:

Solution:

Example Code:

from selenium import webdriver
import time
# Step 1: Set up the WebDriver
driver = webdriver.Chrome() # Replace with the driver for your browser
# Step 2: Navigate to the target webpage
driver.get("URL_OF_THE_PAGE_WITH_FILE_UPLOAD") # Replace with the target URL
# Step 3: Locate the file input element
file_input = driver.find_element("css selector", "input[type='file']") # Adjust the selector as needed
# Step 4: Provide the file path to upload
file_path = r"C:path oyour ile.txt" # Replace with the full path to the file
file_input.send_keys(file_path)
# Step 5: Wait to observe the result (optional)
time.sleep(5)
# Step 6: Close the browser
driver.quit()

Explanation:

Locate the File Input Element:

Use an appropriate locator (e.g., "css selector", "id", "name") to find the element on the page.

Use send_keys():

Pass the absolute file path as a string to the send_keys() method. Selenium simulates entering the file path in the file input field.

File Path:

Ensure the file path is correct and exists on your local machine.

Use raw strings (r"path") or escape backslashes (e.g., C:\path\to\file.txt) to avoid issues with special characters.

Notes:

This method bypasses the need to interact with the native file picker window because Selenium cannot control OS-level windows.

If there is no element and the file upload dialog is handled by custom scripts, use tools like AutoIt, PyAutoGUI, or Robot Framework for OS-level automation.

Example Using PyAutoGUI (For Custom File Dialogs):

import pyautogui
import time
# Open the file upload dialog using Selenium
browse_button = driver.find_element("id", "browse-button")
browse_button.click()
# Wait for the file upload dialog to appear
time.sleep(2)
# Enter the file path and press Enter
pyautogui.write(r"C:path oyour ile.txt")
pyautogui.press("enter")

Output:

When the script runs successfully, the specified file will be selected and uploaded to the web application.



Your Answer

Interviews

Parent Categories