selenium(java)窗口截图的应用--异常后截图

当自动化测试用例出现错误时,为便于理解错误原因,本文介绍了如何使用selenium WebDriver的getScreenshotAs()方法进行窗口截图。结合具体示例,优化了异常发生后的截图流程,截图文件以时间戳命名,确保每个错误的独特标识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自动化用例是由程序去执行,因此有时候打印的错误信息并不十分明确。如果在脚本执行出错的时候能对当前窗口截图保存,那么通过图片就可以非常直观地看出出错的原因。WebDriver 提供了截图函数getScreenshotAs()来截取当前窗口。


根据虫师的demo,我结合实际做了优化,效果不错。抛异常后截图,并且截图以时间戳命名区分。


package ScreenShot;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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 ScreenShotCSDN {
	public static void main(String[] args) throws IOException {
		WebDriver driver = new FirefoxDriver();
		// 打开CSDN登录页面
		driver.get("https://passport.csdn.net/account/login?ref=toolbar");
		
		try {
			//输入用户名和密码,此处专门将密码输入错误,造出异常现象
			driver.findElement(By.xpath(".//*[@id='username']")).sendKeys("ab_2016");
			driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("aaa");
			driver.findElement(By.xpath(".//*[@id='fm1']/input[6]")).click();
			// 由于密码输入错误,所以无法进入登陆后页面,也就无法进行点击“设置”的操作,因此如我们所愿,进入catch分支
			driver.findElement(By.linkText("设置")).click();
		} catch (Exception e) {
			// 打印异常原因,控制台也会打印
			System.out.println("======exception reason=======" + e);
			//图片名称加时间戳
			String dateString = getDateFormat();
			
			// getScreenshotAs()对当前窗口进行截图
			File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
			// 需要指定图片的保存路径及文件名
			FileUtils.copyFile(srcFile, new File("e:\\selenium\\" + dateString + ".png"));
			e.printStackTrace();
		}
		
	}
	
	public static String getDateFormat(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String dateString = sdf.format(date);
		return dateString;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值