When uploading a file with Python Selenium, you can select the file with send_keys (/ path / to / file)
for the input element with type =" file "
[^ selenium-send-keys]. In most cases, the input element doesn't seem to be there, but it's hidden in CSS, so in most cases this is the way to go (modify the CSS so that the webdriver can access the input element. It is necessary.)
However, some pages do not use the input element for file selection, and you may need to select files by dragging and dropping. In such a case, the following method is effective.
Use the code from florentbr / # wd-drop-file.py --GitHub Gist.
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
import os.path
with open("wd-drop-file.min.js", "r") as f:
JS_DROP_FILES = f.read()
def drop_files(element, files, offsetX=0, offsetY=0):
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 isinstance(files, list) else [files]) :
if not os.path.isfile(file) :
raise FileNotFoundError(file)
paths.append(file if isLocal else element._upload(file))
value = '\n'.join(paths)
elm_input = driver.execute_script(JS_DROP_FILES, element, offsetX, offsetY)
elm_input._execute('sendKeysToElement', {'value': [value], 'text': value})
WebElement.drop_files = drop_files
#Below is an example of use
driver = webdriver.Chrome()
driver.get("https://react-dropzone.js.org/")
dropzone = driver.find_element_by_css_selector("[data-preview='Basic example'] [style]")
dropzone.drop_files("C:\\temp\\image1.png ")
If you look at Gist, you can see everything, but the code looks like this. See Gist for wd-drop-file.min.js
. The original entered JS_DROP_FILES
directly, but this code reads from an external file.
Recommended Posts