java 自動化 web 自動化之文件上傳

檸檬班軟件測試 發佈 2020-05-16T20:22:20+00:00

背景在做web自動化時,我們經常會碰到一些場景需要進行文件上傳,而文件上傳打開的窗口屬於windows空格,通過Selenium是操作不了的,此篇文章給大家介紹幾種實現方法方法一:sendKeys前提條件: 文件上傳元素是input標籤,並且type為file才可以使用此種方法以

背景

在做web自動化時,我們經常會碰到一些場景需要進行文件上傳,而文件上傳打開的窗口屬於windows空格,通過Selenium是操作不了的,此篇文章給大家介紹幾種實現方法

方法一:sendKeys

前提條件: 文件上傳元素是input標籤,並且type為file才可以使用此種方法

以我在本地的fileupload.html文件為例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上傳示例</title>
</head>
<body>
    <input type="file" id="fu" value="選擇文件">
</body>
</html>

測試代碼如下:

ChromeDriver driver = new ChromeDriver();
driver.get("D:\\fileupload.html");
Thread.sleep(2000);
driver.findElement(By.id("fu")).sendKeys("D:\\java_auto\\test.png");

此方法的核心在於元素是input類型,可以藉由sendKeys方法去輸入上傳文件的路徑即可

方法二:AutoIT

針對不是input類型的元素,我們可以使用第三方的自動化工具,比如:Auto,對windows控制項元素進行操作

以下是其官網介紹:

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys).

翻譯過來就是:

AutoIT是類似於Basic腳本語言的免費軟體,利用它我們可以實現對windows的GUI介面進行自動化操作,balabala...

官網地址:https://www.autoitscript.com/site/autoit/

強烈建議先去看官方文檔:https://www.autoitscript.com/autoit3/docs/,對工具的使用和腳本編寫語法描述的非常詳細

step1:下載安裝

下載頁面在這裡:https://www.autoitscript.com/site/autoit/downloads/

點擊下載即可,下載完無腦下一步直到安裝完畢



安裝完畢會有如下幾個應用:



其中我們用得到的有:

  • AutoIT Window Info 識別Windows元素信息
  • Complie Script to .exe 將AutoIT編寫的腳本編譯成exe可執行文件
  • Run Script 運行AutoIT腳本
  • SciTE Script Editor 編寫AutoIT腳本

注意:官方推薦使用X86版本,這樣兼容性問題會少些

step2:使用AutoIT

1、將上傳的Windows窗口打開 2、打開AutoIT Window Info 工具,Finder Tool下的圖標一直按住,選擇窗口中要識別的元素(文件名後面的輸入框以及打開按鈕),分別記錄下此時的Tile、Class等信息



3、打開SciTE Script Editor,開始進行腳本編寫(注意元素的定位是由Class和Instance進行拼接的,如Class為Edit,Instance為1,那麼定位表達式為Edit1)

;等待「打開」窗口
WinWaitActive("打開")
;休眠2秒
Sleep(2000)
;在輸入框中寫入上傳文件的路徑
ControlSetText("打開", "", "Edit1", "d:\java_auto\test.png")
;休眠2秒
Sleep(2000)
;點擊打開按鈕
ControlClick("打開", "","Button1");

4、選擇工具欄上面的 Tools-Go 先去運行下腳本,試運行OK之後將腳本保存,後綴為au35、選擇Complie Script to .exe工具把腳本編譯為exe文件6、Java代碼本地執行exe文件

ChromeDriver driver = new ChromeDriver();
driver.get("D:\\fileupload.html");
Thread.sleep(2000);
driver.findElement(By.id("fu")).click();
//Java運行時對象
Runtime runtime = Runtime.getRuntime();
try {
    //執行
    runtime.exec("D:\\upload.exe");
}catch (IOException e){
    e.printStackTrace();
}

來看看運行效果


關鍵字: