截屏功能

[b]1、使用webdriver封装的API函数截图[/b]
//截屏功能,并以当前时间戳为文件名保存在指定目录下
public void takeScreenShot(){
String dir_name = "screenshot"; //定义一个截图存放的目录名,此处为当前目录的screenshot目录下
//判断目录是否存在
if(!(new File(dir_name).isDirectory())){
//如果不存在则新建目录
new File(dir_name).mkdir();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
//格式化当前时间,例如20120406-165210
String time = sdf.format(new Date());

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try{
//将截图存放到指定目录,并以当前时间戳作为文件名保存
FileUtils.copyFile(scrFile, new File(dir_name + File.separator + time + ".png"));
}catch(IOException e){
e.printStackTrace();
}
}


[b]2、使用java提供的接口截图[/b]
 //获取元素坐标并截图
public void elePosition(WebDriver driver,By location){
String js = "document.getElementById('su').style.border='2px solid red'";
((JavascriptExecutor)driver).executeScript(js);

WebElement ele = driver.findElement(location);
Point p = ele.getLocation();
Dimension d = ele.getSize();
System.out.println("x:"+p.x+" y:"+p.y);
System.out.println("height:"+d.height+" width:"+d.width);
screenshot(p.x,p.y,d.width,d.height);
}

//截图
public void screenshot(int x,int y,int w,int h){
String dir_name = "screenshot"; //定义一个截图存放的目录名,此处为当前目录的screenshot目录下
//判断目录是否存在
if(!(new File(dir_name).isDirectory())){
//如果不存在则新建目录
new File(dir_name).mkdir();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
//格式化当前时间,例如20131016-165210
String time = sdf.format(new Date());

try {
//屏幕的分辨率
int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); //要截取的宽度
int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); //要截取的高度
//System.out.println(width+" "+height);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(new Rectangle(width,height));
image = image.getSubimage(x, y, w+100, h+200);
ImageIO.write (image, "png" , new File(dir_name + File.separator + time + ".png")); //保存到硬盘
}catch(AWTException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}


以上两种方法都能成功的截取图片,区别在于:
第一种是截取整个浏览器页面
第二种是截取指定x轴、y轴距离以及图片大小
各位测试道友可根据自己实际需求选择方案。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值