標籤:小強測試品牌 python 自動化測試 selenium
問題
在做web端ui層自動化的時候會碰到檔案上傳的操作,經常有朋友問到,這裡總結一下
解決方案
第一種:type=file的上傳檔案,類似如下的
650) this.width=650;" src="http://p3.pstatp.com/large/322c0000ec9ccd6d16e9" alt="python+selenium+autoit實現檔案上傳" style="border-style:none;margin:10px auto;" />
使用類似這樣的代碼就可以完成:
driver.find_element(‘name‘,‘file‘).send_keys(‘./小強測試品牌.png‘)
第二種:就是第一種除外的,實現起來較為麻煩,這裡用到了autoit,大致步驟如下:
1、下載並安裝autoit,之後在開始菜單可以看到如下
650) this.width=650;" src="http://p9.pstatp.com/large/32120003bd8797e6513c" alt="python+selenium+autoit實現檔案上傳" style="border-style:none;margin:10px auto;" />
AutoIt Windows Info 用於識別Windows控制項資訊
Compile Script to.exe 用於將AutoIt產生 exe 執行檔案
Run Script 用於執行AutoIt指令碼
SciTE Script Editor 用於編寫AutoIt指令碼
2、上傳功能如下
650) this.width=650;" src="http://p1.pstatp.com/large/322d00038f0be9414e2c" alt="python+selenium+autoit實現檔案上傳" style="border-style:none;margin:10px auto;" />
3、識別元素,主要是中的檔案名稱輸入框和開啟按鈕,使用AutoIt Windows Info完成,記錄結果如下:
檔案名稱輸入框的class 為“Edit”,Instance為“1”
開啟按鈕的class 為“Button”,Instance為“1”
4、編寫指令碼,使用SciTE Script Editor,內容如下:
ControlFocus("檔案上傳", "","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("檔案上傳", "", "Edit1","D:python_workspaceQiangSEAutopic小強測試品牌.jpg")
Sleep(2000)
ControlClick("檔案上傳", "","Button1");
上述代碼中特別需要注意“檔案上傳”字樣是你點擊上傳按鈕之後彈出的對話方塊的title,可能每個系統會不一樣
5、驗證指令碼
保證頁面的上傳對話方塊開啟,然後運行指令碼tools>go
6、開啟Compile Script to.exe工具,將其產生為exe可執行檔
650) this.width=650;" src="http://p1.pstatp.com/large/321000043d11d1f8d04b" alt="python+selenium+autoit實現檔案上傳" style="border-style:none;margin:10px auto;" />
7、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 類比按鍵
本文出自 “小強效能自動化測試品牌” 部落格,請務必保留此出處http://xqtesting.blog.51cto.com/4626073/1958454
python+selenium+autoit實現檔案上傳