selenium提供了截圖的功能,分別是接口是TakesScreenshot和類RemoteWebDriver。該功能是在運行測試用例的過程中,需要驗證某個元素的狀態或者顯示的數值時,可以將屏幕截取下來進行對比;或者在異常或者錯誤發生的時候將屏幕截取並保存起來,供后續分析和調試所用。
下面以百度首頁為例學習一下截圖功能如何使用。實例代碼如下:
package com.qianli.selenium;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.google.common.io.Files;
public class TestScreenshot {
public static void main(String[] args) {
//selenium3需要加載firefox的geckodriver.exe
String path = "C:\\Program Files\\Mozilla Firefox\\geckodriver.exe" ;
//設置firefox的系統屬性
System.setProperty("webdriver.gecko.driver", path) ;
WebDriver driver = new FirefoxDriver();
driver.get("http://www.baidu.com");
//指定了OutputType.FILE做為參數傳遞給getScreenshotAs()方法,其含義是將截取的屏幕以文件形式返回。
//driver需要強制轉換為RemoteWebDriver對象,可以通過eclipse提示進行處理
File scrFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
try {
//利用FileUtils工具類的copy()方法保存getScreenshotAs()返回的文件對象。
//看到網上有使用File.copyFile()方法,我這里測試的結果需要使用copy()方法
Files.copy(scrFile, new File("d:\\screenfile.png"));
} catch (IOException e) {
// 異常處理
e.printStackTrace();
}
driver.quit();
}
}
注意:
TakesScreenshot接口是依賴於具體的瀏覽器API操作的,我在谷歌Chrome瀏覽器做自動化時可用,用Firefox和IE瀏覽器均報錯,換成RemoteWebDriver就沒有問題了。
