-->

Upload a file using WebDriver & PyWinAuto

2019-09-09 16:34发布

问题:

I have a python script that tries to upload a file from my PC to a web application. I press via WebDriver the specific upload button in the browser and then a Win7 explorer window opens for me to navigate and select the desired file to upload. How could I manipulate this window with pywinauto?

optional: could this be done in linux as well (with an appropriate library I suppose) ?

This is my sample code:

wd.find_element_by_css_selector("img.editLecturesButtons.fromVideo").click()
#switch to the lightbox
wd.switch_to_frame(int("1"))
#hit upload
wd.find_element_by_xpath("//*[@id='fileUpload']").click()
#TODO
import os,pywinauto.application
file = os.path.normpath("C:\Users\me\Desktop\image.jpg")
....

回答1:

I agree with Mark, you should try the Webdriver methods. Regard to pywinauto, code may looks like:

import pywinauto

pwa_app = pywinauto.application.Application()
w_handle = pywinauto.findwindows.find_windows(title=u'Open', class_name='#32770')[0]
window = pwa_app.window_(handle=w_handle)
ctrl = window['Name']
ctrl.SetText(file)
ctrl = window['OK']
ctrl.Click()

This sollution only for Windows, since pywinauto uses win32 api.