关于Selenium的UI自动化测试屏幕截图功能实例代码

UI自动化测试执行过程中,当遇到检查失败的情况,往往会发现打印的log并不能有效地帮助我们定位问题。我们需要失败时刻的屏幕截图来重现当时的失败场景,进而排查出错原因。

基于这种需求可以使用Selenium的屏幕截图功能。

实现代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

import java.io.File;

import java.io.IOException;

import org.apache.commons.io.FileUtils;

import org.apache.commons.lang3.time.DateUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.interactions.Actions;

public static void takeScreeshot(String screenPath, WebDriver chrome){

   try {

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

    File scrFile = ((TakesScreenshot) chrome)

       .getScreenshotAs(OutputType.FILE); // 关键代码,执行屏幕截图,默认会把截图保存到temp目录

    FileUtils.copyFile(scrFile, new File(screenPath)); //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

    } catch (IOException e) {

     System.out.println("Screen shot error: " + screenPath);

     System.out.println("该错误可以查看截图:"+screenPath);

   } catch (Exception e) {

    // TODO: handle exception

   }

  }

   

   public static void takeScreenshot(WebDriver chrome,String imgName) {

    String screenName=imgName+DateUtils.MILLIS_PER_DAY+".jpg";

    String fileString= "D:\\selenium\\SchoolpalERP_QTP\\image";     

    if (!(new File(fileString).isDirectory())) { // 判断是否存在该目录

     new File(fileString).mkdir(); // 如果不存在则新建一个目录

    }

    File dir = new File(fileString);

    if (!dir.exists())

     dir.mkdirs();

    String screenPath = dir.getAbsolutePath() + "\\" + screenName;

    takeScreeshot(screenPath, chrome);

   }

  最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值