Search code examples
pythonseleniumfile-uploadopenfiledialog

How to avoid the open file dialog box by UPLOADING the file directly with Python and Selenium only?


I'm processing a website that requires to upload files with an "open file dialog".

Here is the setup:

import selenium
from selenium import webdriver
browser = webdriver.Chrome(executable_path=r"C:\Users\PC\Documents\Downloads\chromedriver.exe")
browser.maximize_window()

filename = '24_bit_fixed.wav'
folder = 'C:\\Users\\PC\\Documents\\Downloads\\'
path = folder + filename

And this is the tricky part:

NewRelease_Upload = '/html/body/ui-view/sections-list-modal/loeschen-modal/div/div[1]/div[3]/loeschen-modal-footer/button/div[1]/div[2]/span'
#browser.find_element_by_id("").send_keys(path)
#browser.find_element_by_xpath(NewRelease_Upload).send_keys(path)

I know that if there were an id, I could easily use these two lines and therefore avoid the open file dialog box:

browser.switch_to_frame(0)
browser.find_element_by_id("something").send_keys(path)

But there is neither an id nor such frame on the website and I'm trying to do it with selenium only without pywinauto.


Solution

  • usually you do not need to mess with open file dialog. usually all you need to do is find the <input type="file"> element. then type the full filename using elem.send_keys('fullfilename'). then submit the form.

    if you do not have an id to conveniently find the element (and no access to the html to insert an id in the first place) then you can try to find the element using other methods. for example using the xpath //input[@type='file']. here are more: https://selenium-python.readthedocs.io/locating-elements.html

    sometimes the website mucks around with the input element so that it is hidden or otherwise obfuscated. then you have to resort to heavier tools.

    for example use javascript to "free" the input element first: Python-Selenium "input type file" upload

    or use javascript to type the filename in the input element: Webdriver: File Upload

    if you need help finding the <input type="file"> element or typing in the filename then please post another question detailing the exact problem and post the relevant html source code.

    for completeness: selenium has no features to interact with the file open dialog. either avoid the dialog by using the <input type="file"> element or use gui automation tools.