python+selenium+autoit實現文件上傳

問題

在作web端ui層自動化的時候會碰到文件上傳的操做,常常有朋友問到,這裏總結一下python

解決方案

第一種:type=file的上傳文件,相似以下的web

python+selenium+autoit實現文件上傳

使用相似這樣的代碼就能夠完成:ide

driver.find_element('name','file').send_keys('./小強測試品牌.png')工具

第二種:就是第一種除外的,實現起來較爲麻煩,這裏用到了autoit,大體步驟以下:測試

一、下載並安裝autoit,以後在開始菜單能夠看到以下ui

python+selenium+autoit實現文件上傳

AutoIt Windows Info 用於識別Windows控件信息spa

Compile Script to.exe 用於將AutoIt生成 exe 執行文件orm

Run Script 用於執行AutoIt腳本blog

SciTE Script Editor 用於編寫AutoIt腳本ip

二、上傳功能以下

python+selenium+autoit實現文件上傳

三、識別元素,主要是上圖中的文件名輸入框和打開按鈕,使用AutoIt Windows Info完成,記錄結果以下:

文件名輸入框的class 爲「Edit」,Instance爲「1」

打開按鈕的class 爲「Button」,Instance爲「1」

四、編寫腳本,使用SciTE Script Editor,內容以下:

ControlFocus("文件上傳", "","Edit1")

WinWait("[CLASS:#32770]","",10)

ControlSetText("文件上傳", "", "Edit1","D:python_workspaceQiangSEAutopic小強測試品牌.jpg")

Sleep(2000)

ControlClick("文件上傳", "","Button1");

上述代碼中特別須要注意「文件上傳」字樣是你點擊上傳按鈕以後彈出的對話框的title,可能每一個系統會不同

五、驗證腳本

保證頁面的上傳對話框打開,而後運行腳本tools>go

六、打開Compile Script to.exe工具,將其生成爲exe可執行文件

python+selenium+autoit實現文件上傳

七、python腳本中調用

up=self.driver.find_element('class name','avatar-uploader-trigger')

up.find_element('class name','ant-btn').click()

os.system('D:\python_workspace\QiangSEAuto\upload.exe')

time.sleep(20)

其餘

其實還有其餘的解決方法,感興趣的自行研究吧,好比還能夠利用以下的方式:

Python pywin32庫,識別對話框句柄,進而操做

SendKeys 庫

keybd_event 模擬按鍵

相關文章
相關標籤/搜索