Selenium 使用 JavaScript 來模擬操作。因此,它不支持諸如上載窗口、下載窗口或身份認證窗口之類的瀏覽器元素。對於非主要窗口,配置瀏覽器跳過彈出窗口。
跳過圖1 中安全信息窗口的解決方案是打開 Tools > Internet Options > Custom Level。然後啓用 Display mixed content。
配置 Internet Explorer 跳過非主要窗口會減少或消除運行測試用例時不必要的處理。但是如果配置了 Firefox,那麼將它保存爲新的配置文件,並利用定製的配置文件啓動服務器。在關於測試 HTTPS 網站的一節中提到了這樣做的原因。
對於上載/下載窗口,最好是處理而不是跳過它們。爲了避免 Selenium 的侷限性,一種建議是使用 Java 機器人 AutoIt 來處理文件上載和下載問題。AutoIt 被設計來自動化 Window GUI 操作。它可以認識大多數 Window GUI,提供很多 API,並且很容易轉換爲 .exe 文件,這樣的文件可以直接運行或者在 Java 代碼中調用。清單 1 演示了處理文件上載的腳本。這些腳本的步驟是:
- 根據瀏覽器類型確定上載窗口標題。
- 激活上載窗口。
- 將文件路徑放入編輯框中。
- 提交。
;first make sure the number of arguments passed into the scripts is more than 1 If $CmdLine[0]<2 Then Exit EndIf handleUpload($CmdLine[1],$CmdLine[2]) ;define a function to handle upload Func handleupload($browser, $uploadfile) Dim $title ;declare a variable ;specify the upload window title according to the browser If $browser="IE" Then ; stands for IE; $title="Select file" Else ; stands for Firefox $title="File upload" EndIf if WinWait($title,"",4) Then ;wait for window with title attribute for 4 seconds; WinActivate($title) ;active the window; ControlSetText($title,"","Edit1",$uploadfile) ;put the file path into the textfield ControlClick($title,"","Button2") ;click the OK or Save button Else Return False EndIf EndFunc |
在 Java 代碼中,定義一個函數來執行 AutoIt 編寫的 .exe 文件,並在單擊 browse 之後調用該函數。
public void handleUpload(String browser, String filepath) { String execute_file = "D://scripts//upload.exe"; String cmd = "/"" + execute_file + "/"" + " " + "/"" + browser + "/"" + " " + "/"" + filepath + "/""; //with arguments try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); //wait for the upload.exe to complete } catch (Exception e) { e.printStackTrace(); } } |
清單 3 是處理 Internet Explorer 中下載窗口的 AutoIt 腳本。Internet Explorer 和 Firefox 中的下載腳本各不相同。
清單 3. 處理 Internet Explorer 中下載的 AutoIt 腳本
If $CmdLine[0]<1 Then Exit EndIf handleDownload($CmdLine[1]) Func handleDownload($SaveAsFileName) Dim $download_title="File Download" If WinWait($download_title,"",4) Then WinActivate($download_title) Sleep (1000) ControlClick($download_title,"","Button2","") Dim $save_title="Save As" WinWaitActive($save_title,"",4) ControlSetText($save_title,"","Edit1", $saveAsFileName) Sleep(1000) if FileExists ($SaveAsFileName) Then FileDelete($SaveAsFileName) EndIf ControlClick($save_title, "","Button2","") Return TestFileExists($SaveAsFileName) Else Return False EndIf EndFunc |
AutoIt 腳本很容易編寫,但是依賴於瀏覽器類型和版本,因爲不同的瀏覽器和版本中,窗口標題和窗口控件類是不相同的。