WebDrive API (十)对当前浏览器窗口进行截屏并保存到本地

新引入的包:

import java.io.File;
import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import java.io.IOException;
  1. 对当前浏览器打开的页面进行截图,保存到一个File对象中

    File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    
  2. 将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();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Summer@123

不积跬步无以至千里,感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值