Skip to content

Instantly share code, notes, and snippets.

@florentbr
Last active January 4, 2022 04:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save florentbr/0eff8b785e85e93ecc3ce500169bd676 to your computer and use it in GitHub Desktop.
Save florentbr/0eff8b785e85e93ecc3ce500169bd676 to your computer and use it in GitHub Desktop.
Selenium - Upload a file
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import NoSuchElementException
import os.path
def upload_files(element, *files):
driver = element.parent
isLocal = not driver._is_remote or '127.0.0.1' in driver.command_executor._url
paths = []
# ensure files are present, and upload to the remote server if session is remote
for file in files :
if not os.path.isfile(file) :
raise FileNotFoundError(file)
paths.append(file if isLocal else element._upload(file))
# intercept the file input from the click event and disable the file picker from the OS
driver.execute_script("""\
var element = arguments[0];
window.wd1b2ce5c94f7c = null;
element.ownerDocument.addEventListener('click', function handler(event) {
if (event.target.type === 'file') {
element.ownerDocument.removeEventListener('click', handler, true);
window.wd1b2ce5c94f7c = event.target;
event.preventDefault();
event.stopPropagation();
}
}, true);
""", element)
# trigger a click which should propagate to the file input (same as pressing enter)
element.click()
# get the file input that received the click
elm_input = driver.execute_script("return window.wd1b2ce5c94f7c;")
if elm_input is None :
raise NoSuchElementException("Failed to detect the file input")
# assign the files to the file input
value = '\n'.join(paths)
elm_input._execute('sendKeysToElement', {'value': [value], 'text': value})
WebElement.upload_files = upload_files
############################# USAGE EXAMPLE #############################
driver = webdriver.Chrome()
driver.get("https://react-dropzone.js.org/")
driver.find_element_by_css_selector(".dropzone > *")\
.upload_files('c:\\temp\\image1.png')
@king-huangkoyung
Copy link

what is window.wd1b2ce5c94f7c;? because I received a NoSuchElementException result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment