In the study selenium automated testing, encountered file upload, author of the book skips lightly, avoiding the actual job requirements.
In line with the idea of proceeding from reality, check the information on the Internet, end-use win32 library to complete the file upload.
Installation pypiwin32 library: pip install pypiwin32
Reference https://www.cnblogs.com/linuxchao/p/linuxchao-selenium-upload_file.html
===============================================================
Return to the topic, the following content is the practical operation of the code, hoping to be able to comment things more clearly described.
win32con Import
Import win32gui
from SLEEP Time Import
from selenium.webdriver.common.action_chains Import ActionChains
from the Selenium Import webdriver
DEF uploadFile (Browser: str, File: str):
# browser to open the window title names are different
browser_type = {
'Firefox' : 'Upload file',
'Chrome': 'open',
'IE': 'select the file to load'
}
SLEEP (2)
# tools WinSpy, positioned "open" window, class number # 32770
dialog = win32gui.FindWindow('#32770',browser_type[browser])
# 需要一级一级找子窗口edit;;;在工具WinSpy右侧可以看到“打开”窗口的结构:#32770 “打开”---ComboBoxEx32---ComboBox---Edit
ComboBoxEx32 = win32gui.FindWindowEx(dialog,0,"ComboBoxEx32",None)
ComboBox = win32gui.FindWindowEx(ComboBoxEx32,0,"ComboBox",None)
edit = win32gui.FindWindowEx(ComboBox,0,"Edit",None)
button = win32gui.FindWindowEx(dialog,0,"Button",None)
win32gui.SendMessage(edit,win32con.WM_SETTEXT,None,file)
win32gui.SendMessage(dialog,win32con.WM_COMMAND,1,button)
if __name__ == '__main__':
driver = webdriver.Chrome()
driver.get(r'C:\Users\Administrator\PycharmProjects\webAutoTest\upload_file.html')
element = driver.find_element_by_xpath('//*[@id="upload_file"]')
action = ActionChains(driver)
action.move_to_element(element).click().perform()
action.release()
sleep(3)
uploadFile('chrome',r'C:\driver\chromedriver 64b.exe')
sleep(3)
driver.quit()