如何用Selenium的send_keys向无input标签的拖拽上传区传文件?
send_keys Hey there, let's break down why your initial approach hit that ElementNotInteractableException and how to fix it using Selenium's native send_keys method.
The Root Cause
The element you're targeting (//*[@iconid="drop-image"]) is just the visual icon for the Dropzone component—it's not the actual file input that accepts file paths via send_keys. Styled dropzones like this almost always hide the native <input type="file"> element behind the fancy UI (usually set to display: none or visibility: hidden), so you need to interact with that hidden input instead of the visible icon.
Solution: Target the Hidden File Input
Here's how to make it work:
Locate the hidden native file input
Even if it's not visible in the HTML snippet you shared, Dropzone components always have an associated<input type="file">somewhere inside the<dropzone>tag. Use this XPath to find it:file_input = driver.find_element_by_xpath('//dropzone//input[@type="file"]')Interact with it (two reliable methods)
Since the input is hidden, Selenium might block direct interaction by default—use one of these approaches to get around that:Method 1: Unhide temporarily, send keys, then re-hide
# Locate the hidden input file_input = driver.find_element_by_xpath('//dropzone//input[@type="file"]') # Use JavaScript to make it visible temporarily driver.execute_script("arguments[0].style.display = 'block';", file_input) # Send the file path file_input.send_keys('/home/user/pic/3-1.png') # Optional: Hide it again to preserve the UI driver.execute_script("arguments[0].style.display = 'none';", file_input)Method 2: Directly set the value via JavaScript (no unhiding needed)
If you don't want to modify the UI, you can directly pass the file path to the input using JavaScript:
file_input = driver.find_element_by_xpath('//dropzone//input[@type="file"]') driver.execute_script("arguments[0].value = arguments[1];", file_input, '/home/user/pic/3-1.png')
Why This Works
The native <input type="file"> is the element that actually handles file uploads under the hood. Dropzone's JavaScript library listens for changes on this input and triggers the upload process automatically. Your original approach was targeting a div element (the icon), which can't accept send_keys input—hence the ElementNotInteractableException.
Quick Note on Your PyAutoGUI Workaround
I see you got it working with PyAutoGUI, which simulates manual clicks and keyboard input. That's a solid fallback, but using Selenium's native methods is more reliable: it doesn't depend on your OS's window focus, and it avoids issues with the file dialog popping up in unexpected places.
内容的提问来源于stack exchange,提问作者Oladuwek

