Upload File in Selenium Python

Profile picture for user arilio666

To upload a file in Python using Selenium, follow these steps:

Import the required modules:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from Selenium.webdriver.common.by import By

Configure the Selenium WebDriver:

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

Navigate to the webpage with the file upload element:

driver.maximize_window()
driver.get('http://autopract.com/selenium/upload1/')

Track down the file upload input element:

file_input = driver.find_element(By.XPATH,"//input[@name='files[]']")
  • You may find the file input element using several ways, such as ID, class name, CSS selector, or XPath. Adapt the locator to the structure of the webpage you're working on.

Send the following string to the file input element:

file_path = "D:\iVagus\SelPy\Luffy.png"
file_input.send_keys(file_path)

Fill out the file upload form and submit it.

driver.find_element(By.XPATH,"//button[@type='submit']").click()
  • Locate the proper element and trigger the action if the file upload requires hitting a submit button or any other form submission action.
  • That's all! The file should be uploaded in Python using Selenium. Check that you have the proper rights and follow the file upload requirements on the website.
print(driver.find_element(By.XPATH,"//p[@class='name']").text)

Let us verify that the name of the upload file we sent is the same.

Upload File in Selenium Python

We can see this works!!