codyc4321
codyc4321

Reputation: 9672

upload files with selenium webdriver python

I'd like to use webdriver to pick a file but following other answers they do not work. They say just give the button a filepath, and this doesn't do anything. The upload looks like this after clicking the button:

enter image description here

This is what others say to do but doesn't work:

element = driver.find_element_by_name("file")
element.send_keys("/home/pavel/Desktop/949IH3GNHAo.jpg")

How can I submit files once I'm in a webdriver instance? Thank you

Upvotes: 2

Views: 7554

Answers (4)

Oleg  Mykolaichenko
Oleg Mykolaichenko

Reputation: 627

I'm also had problem with upload using Python and Selenium. It was because upload web form was not visible, and situated under the "upload image". (hidden upload form)

So i've made workaround.

# Try to open page with upload form
driver.get('https://bla.com/library/browser')

# Waiting for upload element with name upload-search-block
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "upload-search-block"))) 

# Relocate hidden upload form using JS 
driver.execute_script("document.getElementById('upload-search-block').style.left='200px';")
driver.execute_script("document.getElementById('upload-search-block').style.top='170px';")

# And upload file in the end 
upload = driver.find_element_by_id('upload-search-block')
upload.send_keys('/tmp/custom_doc.docx')

Good luck.

Upvotes: 2

codyc4321
codyc4321

Reputation: 9672

This problem solved at uploading photos to Craigslist with Python and Selenium

def add_photo(self, filepath_to_photo):
    photo_filepath_input_box = self.driver.find_element_by_xpath("//input[@type='file']")
    photo_filepath_input_box.send_keys(filepath_to_photo) # "/home/cchilders/photos/myhouse/upperrightbedroom/photo1.png"

Upvotes: 3

Alichino
Alichino

Reputation: 1736

Give AutoIT a try.

It's very easy to use and does the job.

Click on the Upload button first with the webdriver script, and then run the AutoIT .exe file with:

import subprocess
subprocess.Popen('[name_of_your_script].exe')

Then give it a wait.until, using expected conditions, so it waits until the file finishes uploading.

An example AutoIT code below will select a file called "AAUPLOADFILE.png":

Local $hWnd=WinWait("[CLASS:#32770]","",10)

ControlFocus($hWnd,"","Edit1")

; Wait for 2 seconds.

  Sleep(2000)

  ControlSetText($hWnd, "", "Edit1", "AAUPLOADFILE.png")

  Sleep(2000)

; Click on the Open button

  ControlClick($hWnd, "","Button1");

Once you've got a script written, right-click the file and select Compile Script, which will create an .exe file.

Upvotes: 3

Joey
Joey

Reputation: 1370

Upload windows are system windows and not in the webview. Selenium webdrivers can only control things inside a webview. You will need to hand off the task of choosing the file to another library like AutoIT.

Upvotes: 0

Related Questions