selenium java截图_selenium3(java)之屏幕截图操作

selenium提供了截图的功能,分别是接口是TakesScreenshot和类RemoteWebDriver。该功能是在运行测试用例的过程中,需要验证某个元素的状态或者显示的数值时,可以将屏幕截取下来进行对比;或者在异常或者错误发生的时候将屏幕截取并保存起来,供后续分析和调试所用。

下面以百度首页为例学习一下截图功能如何使用。实例代码如下:

package com.qianli.selenium;

import java.io.File;

import java.io.IOException;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.remote.RemoteWebDriver;

import com.google.common.io.Files;

public class TestScreenshot {

public static void main(String[] args) {

//selenium3需要加载firefox的geckodriver.exe

String path = "C:\\Program Files\\Mozilla Firefox\\geckodriver.exe" ;

//设置firefox的系统属性

System.setProperty("webdriver.gecko.driver", path) ;

WebDriver driver = new FirefoxDriver();

driver.get("http://www.baidu.com");

//指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。

//driver需要强制转换为RemoteWebDriver对象,可以通过eclipse提示进行处理

File scrFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);

try {

//利用FileUtils工具类的copy()方法保存getScreenshotAs()返回的文件对象。

//看到网上有使用File.copyFile()方法,我这里测试的结果需要使用copy()方法

Files.copy(scrFile, new File("d:\\screenfile.png"));

} catch (IOException e) {

// 异常处理

e.printStackTrace();

}

driver.quit();

}

}

注意:

TakesScreenshot接口是依赖于具体的浏览器API操作的,我在谷歌Chrome浏览器做自动化时可用,用Firefox和IE浏览器均报错,换成RemoteWebDriver就没有问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值