Skip to content

Instantly share code, notes, and snippets.

@YoussofH
Forked from florentbr/#wd-upload-file.py
Created November 1, 2019 23:59
Show Gist options
  • Save YoussofH/0ca0bfe8466e0b5e8839edd6e74317c1 to your computer and use it in GitHub Desktop.
Save YoussofH/0ca0bfe8466e0b5e8839edd6e74317c1 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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment