0
0
Selenium Pythontesting~5 mins

File upload handling in Selenium Python

Choose your learning style9 modes available
Introduction

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.

Testing a job application form where users upload their resumes.
Checking if a profile picture upload works on a social media site.
Verifying that a document upload feature in an online form accepts files.
Ensuring that file size or type restrictions are enforced during upload.
Syntax
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.

Examples
Upload a PDF file by locating the input with ID 'upload'.
Selenium Python
file_input = driver.find_element(By.ID, 'upload')
file_input.send_keys('/Users/john/Documents/resume.pdf')
Upload a JPG image using a CSS selector for the file input.
Selenium Python
file_input = driver.find_element(By.CSS_SELECTOR, 'input[type="file"]')
file_input.send_keys('C:\\Users\\Jane\\Pictures\\photo.jpg')
Sample Program

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.

Selenium Python
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()
OutputSuccess
Important Notes

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.

Summary

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.