Search code examples
pythonseleniumfile-upload

Avoid OS pop-up while uploading file with Selenium in Python


I am using selenium to upload a file. This is a problem because the upload button makes a file explorer window appear which I can't automate to my knowledge. How can I either automate file explorer or upload the file directly from selenium? It should select a specific file from a path to upload.

Any help is greatly appreciated.

This is my code:

upload1 = driver.find_element_by_xpath(upload1xpath)
upload1.send_keys('C:\Users\bodig\Downloads\image1.jpg')

Solution

  • To upload a file without clicking the upload button in most cases you can send your file directly to some element on that page.
    This will be element with input tag name with attribute type='file'. Not the button user clicking but somewhere near it.
    So you can try finding that element with this:

    upload_input = driver.find_element_by_xpath('//input[@type="file"]')
    upload.send_keys('C:\Users\bodig\Downloads\image1.jpg')
    

    If you prefer using css_selector you can use this:

    upload_input = driver.find_element_css_selector('input[type="file"]')
    upload.send_keys('C:\Users\bodig\Downloads\image1.jpg')
    

    To find specific element on your page I have to see the web page