zoukankan      html  css  js  c++  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就没有问题了。

  • 相关阅读:
    《C++必知必会》读书笔记
    看美图是一种享受
    C指针-指向另一指针的指针
    顺序队列基本操作
    Using Windows Live Writer to write first offline blog
    堆和栈的区别 [摘录]
    进程与线程的区别
    《Effective C#》
    析构函数virtual与非virtual区别
    常用SQL语句技法
  • 原文地址:https://www.cnblogs.com/laoluoits/p/8465818.html
Copyright © 2011-2022 走看看