一、文件上傳
文件上傳是自動化中棘手的部分,目前selenium並沒有提供上傳的實現api,所以知道借助外力來完成,如AutoIt、sikuli。
AutoIt , 這是一個使用類似BASIC腳本語言的免費軟件,它設計用於Windows GUI(圖形用戶界面)的自動化操作,利用模擬鍵盤按鍵,鼠標移動和窗口/控件的組合來實現自動化任務;
AutoIt下載鏈接:https://www.autoitscript.com/site/autoit/downloads/ 或者點擊下列圖標進行下載!
1.下載后雙擊進行安裝:autoit-v3-setup.exe
安裝完成如下展示:
2.上傳腳本的編寫
(1) 打開AutoIt Windows Info 工具,鼠標移動到Finder Tool,按住鼠標左鍵拖動到需要識別的windows控件上;
(2) 打開編輯器,根據控件Finder Tool識別到的信息來調用函數編寫腳本;
;ControlFocus(("title","text",controllD)用於識別windows文件上傳窗口 ControlFocus("打開","","") ;向文件名輸入框輸入本地要上傳文件的路徑 ControlSetText("打開","","Edit1","C:\Users\Administrator\Desktop\test\圖片\baidu.png") Sleep(2000) ;點擊上傳窗口中的“打開“按鈕 ControlClick("打開","","Button1")
3.保存腳本文件為ChromFileUpload.au3格式
4.tools=>go,執行腳本驗證(前提是windows窗口必須是打開狀態)
腳本執行結束后:
5.為了這個腳本能被java 程序調用,需要通過Compile Script to .exe (x64)工具生成exe文件
提示Conversion complete轉化完成:將ChromeFileUpload.exe拷貝到項目下
6.java代碼執行exe文件
//實現文件上傳。通過Runtime的靜態方法獲取Runtime對象 Runtime runtime = Runtime.getRuntime(); //通過Runtime對象調用exe方法 runtime.exec("src/test/resources/ChromeFileUpload.exe");
7.實現文件上傳整體代碼如下:
package cn.test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FileUpload { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); WebDriver driver =new ChromeDriver(); try { driver.get("file:///C:/Users/Administrator/Desktop/test/file_up_load.html"); driver.manage().window().maximize(); driver.findElement(By.id("fileUpload")).click(); Thread.sleep(3000); //實現文件上傳。通過Runtime的靜態方法獲取Runtime對象 Runtime runtime = Runtime.getRuntime(); //通過Runtime對象調用exe方法 runtime.exec("src/test/resources/ChromeFileUpload.exe"); Thread.sleep(5000); }catch (Exception e) { e.printStackTrace(); }finally { System.out.println("執行結束,關閉瀏覽器"); driver.quit(); } } }
學習后總結,不足之處,后續修改,未完待續。。。