新引入的包:
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.IOException;
-
对当前浏览器打开的页面进行截图,保存到一个File对象中
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
-
将File对象转换成保存到本地磁盘的图片文件
FileUtils.copyFile(screenFile,new File("E:\\WebAutomationTest\\Screenshot\\test.png"));
完整代码:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CaptureScreenInCurrentWindow {
WebDriver driver;
String baseUrl = "https://www.baidu.com/";
@BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void captureScreen() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
//调用getScreenshotAs方法对当前浏览器打开的页面进行截图,保存到一个File对象中
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
/*获取当前时间,并以当前时间命名*/
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String now = df.format(day);
//定义存放截图的本地路径
String testReport = "E:\\Coding\\JavaCode\\WebAutomationTest\\Screenshot";
//包含当前时间的截图文件名
String fileName = testReport + '\\' + now + ".png";
//System.out.println(fileName); //2020-08-26-16-16-54.png
try {
//把File对象转换为一个保存在本地的"test.png"文件
FileUtils.copyFile(screenFile, new File(fileName));
}catch(IOException e) {
e.printStackTrace();
}
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}