WebDriver应用实例(java)——精确比较网页截图图片

本文介绍了在自动化测试中如何运用WebDriver进行网页截图,并详细阐述了如何精确比对不同时期的网页截图,以此来判断页面是否发生变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在测试过程中,常常需要对核心页面进行截屏,并且使用测试过程中的截图和以前测试过程中的截图进行比对。如果能精确匹配,则认为对比成功;如果页面发生任何细微的变化,都会认为不匹配。

        具体实例如下:

package cn.om.webdriverapi;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestCompareScreenShot {
	WebDriver driver;
	String url;

	@Test
	public void testImageComparison() throws InterruptedException, IOException  {
		driver.get(url);
		//对baidu首页进行截屏,保存为baiduHomePage_actual.jpg
		File screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		Thread.sleep(3000);
		FileUtils.copyFile(screenshot, new File("F:\\workspace\\WebDriver API\\baiduHomePage_actual.jpg"));
		
		//打开截图图片和预期图片
		File fileInput=new File("F:\\workspace\\WebDriver API\\baiduHomePage_actual.jpg");
		File fileOutput=new File("F:\\workspace\\WebDriver API\\baiduHomePage_expected.jpg");
		
		
		/*对两个文件进行像素比对的算法实现。
		 * 获取文件的像素大小,然后使用循环的方式将两张图的所有项目进行一一比对,如有任何一个像素不相同,则退出循环
		 * 将matchFlag变量的值设定为fale
		 * 最后通过断言判断matchflag是否为true,如果为true,则表示两张相同。如果是flase表示两张图片并不是完全匹配。
		 */
		BufferedImage bufileInput=ImageIO.read(fileInput);
		DataBuffer dafileInput=bufileInput.getData().getDataBuffer();
		int sizefileInput=dafileInput.getSize();
		
		
		BufferedImage bufileOutput=ImageIO.read(fileOutput);
		DataBuffer dafileOutput=bufileOutput.getData().getDataBuffer();
		int sizefileOutput=dafileOutput.getSize();
		
		Boolean matchFlag=true;
		if(sizefileInput==sizefileOutput){
			for(int j=0;j<sizefileInput;j++){
				if(dafileInput.getElem(j)!=dafileOutput.getElem(j)){
					matchFlag=false;
					break;
				}
			}
		}else{
			matchFlag=false;
		}
		
		Assert.assertTrue(matchFlag,"测试过程中的截图和期望的截图并不一致");
		
	}

	@BeforeMethod
	public void beforeMethod() {
		System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		url="http://www.baidu.com";
	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值