How to upload a file with Selenium

Browser file controls hand selection to a native picker that WebDriver does not automate. Selenium bypasses that desktop dialog by sending an absolute path to the page's input[type=file] element.

A complete upload test should submit the form and inspect the response returned by the application. A populated file input proves only that the browser accepted the path; it does not prove that the server accepted the file.

The Python example uses local Chrome and a small text fixture stored beside the test script. Remote WebDriver uses a local file detector by default, but the remote server must support file transfer from the test runner to the browser node.

Steps to upload a file with Selenium:

  1. Create sample-upload.txt beside the Selenium test script.
    sample-upload.txt
    Quarterly report
  2. Create upload_file_test.py with the imports and absolute fixture path.
    upload_file_test.py
    from pathlib import Path
    import shutil
     
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
     
     
    upload_file = Path("sample-upload.txt").resolve()
  3. Append the initial browser-session section for the file-selection page.
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    driver_path = shutil.which("chromedriver")
    service = webdriver.ChromeService(executable_path=driver_path) if driver_path else None
    driver = webdriver.Chrome(service=service, options=options)
     
    try:
        driver.get("https://the-internet.herokuapp.com/upload")

    If Chrome cannot start, configure the matching browser driver before continuing.
    Related: How to configure ChromeDriver for Selenium

  4. Add file selection and form submission inside the existing try block.
        file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
        file_input.send_keys(str(upload_file))
        driver.find_element(By.ID, "file-submit").click()

    The absolute path belongs on the file input itself; clicking the control opens an operating system picker that WebDriver cannot automate.

  5. Complete the script with filename verification and browser cleanup.
        uploaded_name = WebDriverWait(driver, 10).until(
            lambda browser: browser.find_element(By.ID, "uploaded-files").text
        )
        assert uploaded_name == upload_file.name, uploaded_name
        print(f"Uploaded: {uploaded_name}")
    finally:
        driver.quit()

    The assertion fails when the response does not name the selected file, so the test checks server-side upload completion rather than file-input state alone.
    Related: How to use explicit waits in Selenium

  6. Run the completed upload test from the directory containing both files.
    $ python3 upload_file_test.py
    Uploaded: sample-upload.txt