How to upload file using selenium webdriver+python How to upload file using selenium webdriver+python selenium selenium

How to upload file using selenium webdriver+python


Putting a file name in dropzone hidden input works fine. This should get you going.

upload_file = driver.find_element_by_css_selector('.dz-hidden-input')data_file = Path(__file__).parent / "test_file.txt"logging.debug("data_file: %s", data_file)assert data_file.exists()upload_file.send_keys(str(data_file))assert driver.find_element_by_css_selector('.dz-image').is_displayed()


I did it!Just pip install -U pyautoit

then import autoitautoit.win_wait_active("File Upload", 5)autoit.send(os.path.join("path"))autoit.send("{ENTER}")

Works ok :)


Generally, no.

Selenium can only operate your web browser. When you click any kind of an element that opens a file browser window, this window is provided by your operating system, not the web browser. This is why you can't interact with it in selenium.

IF your web page accepts drag and drop, you might be able to hoodwink it by using sendkeys to send something like file://path/to/your/file as this is what drag and drop actually does, and then using action chains to move your mouse to the element and perform a "drop" by sending the element a release button event. See for example Unable to perform click action in selenium python

for ideas how to use action chains.

This is notoriously unreliable, though. If you are planning to automate posts to, say social media sites, you are probably out of luck, as their upload mechanisms are somewhat more complicated to prevent spamming using robots.

You might want to investigate tools that allow controlling the whole GUI of your computer instead of just the browser. You could then use Selenium to try to locate the absolute position of the drag and drop field, and feed this to an external automator script that clicks on your image, drags it to that spot and drops it there.

Hannu