Selenium提供了截圖的功能,其接口是 TakesScreenshots。
該功能可以在異常或者錯誤發生的時候將屏幕截取並保存起來,供後續分析和調試所用;這個TakesScrernshot類主要是來獲取瀏覽器窗體的內容,不包括瀏覽器的菜單或者桌面等。
下面我們以百度新聞的首頁爲例來實現截圖的功能
首先我們先在我們的src源文件夾下面新建一個文件夾叫做Screenshots用來存放我們的截圖文件
package com.yumeihu.D1;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShoot {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.baidu.com/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Thread.sleep(3000);
//打印百度地址
System.out.println("已經成功進入:"+ driver.getTitle());
//進入到新聞頁
driver.findElement(By.xpath(".//*[@id='u1']/a[1]")).click();
//調用截圖方法 ,指定了OutputType.FILE做爲參數傳遞給getScreenshotAs()方法,其含義是將截取的屏幕以文件形式返回
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// 拷貝截圖文件到我們文件夾下./Screenshots,
//FileUtils.copyFile(file1,file2); file1,file2都是文件類型File; 把file1拷貝到file2;這裏你可以自己調整圖片格式
FileUtils.copyFile(src, new File(".\\Screenshots\\screen.png"));
System.out.println("已經截圖完畢");
}
catch (IOException e) //IOException 是說萬一拿不到這個截圖文件,就拋出異常
{
System.out.println(e.getMessage());
}
}
}
可以在我們之前創建的文件夾中看到圖片已經截取成功。