File upload handling lets you test if a website accepts files correctly. It checks if users can send files like images or documents through a form.
File upload handling in Selenium Python
element = driver.find_element(By.CSS_SELECTOR, 'input[type="file"]') element.send_keys('/path/to/your/file')
Use the send_keys() method to set the file path directly on the file input element.
Make sure the file input element is visible or accessible; otherwise, Selenium might throw an error.
file_input = driver.find_element(By.ID, 'upload') file_input.send_keys('/Users/john/Documents/resume.pdf')
file_input = driver.find_element(By.CSS_SELECTOR, 'input[type="file"]') file_input.send_keys('C:\\Users\\Jane\\Pictures\\photo.jpg')
This script opens a sample page with a file upload button, finds the file input, and sets a file path to upload. It prints a success message if the file path is set.
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup WebDriver (make sure the driver executable is in PATH) driver = webdriver.Chrome() try: driver.get('https://www.w3schools.com/howto/howto_html_file_upload_button.asp') time.sleep(2) # wait for page to load # Locate the file input element file_input = driver.find_element(By.CSS_SELECTOR, 'input[type="file"]') # Provide the file path to upload file_input.send_keys('/path/to/samplefile.txt') print('File upload input set successfully.') finally: time.sleep(2) # wait to see the result driver.quit()
Use absolute file paths to avoid errors.
Some websites hide the file input; in that case, you may need to remove 'hidden' attributes or use JavaScript.
File upload does not actually send the file until the form is submitted.
File upload testing uses send_keys() on file input elements.
Always locate the correct input element with reliable selectors.
Use absolute paths and ensure the element is accessible.