需要引入的基础jar包
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
package com.property;
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;
import org.testng.annotations.Test;
public class ScreenShot {
@Test
public void screenshot() throws IOException {
WebDriver driver = new FirefoxDriver();
// 打开CSDN登录页面
driver.get("http://sso.cserver.com.cn/sso.web/login?service=http%3A%2F%2Fmy.cserver.com.cn%2Fmysystem%2FsaasMysystem.do%3Flayout%3Dsaas");
//try {
//输入用户名和密码,此处专门将密码输入错误,造出异常现象
driver.findElement(By.xpath(".//*[@id='username']")).sendKeys("aaa@163.com");
driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("aaa");
driver.findElement(By.xpath(".//*[@name='button1']")).click();
driver.manage().window().maximize();
// 由于密码输入错误,所以无法进入登陆后页面,也就无法进行点击“设置”的操作,因此如我们所愿,进入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(".\\ScreenShots\\" + dateString + ".png"));
//e.printStackTrace();
//}
}
public static String getDateFormat(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = sdf.format(date);
return dateString;
}
}
参考二:引自:https://www.cnblogs.com/tobecrazy/p/3599568.html