How to compare two images/screenshot in Selenium?

Опубликовано: 07 Апрель 2024
на канале: Programmer World
251
3

In this video I have shown how to compare two screenshots(expected vs actual images) in selenium using Ashot() api.

   • How to take screenshot of particular ...  
   • Selenium - How to take screenshot of ...  
   • How to take CSS Selector/Xpath using ...  
   • How to write xpath in Selenium when p...  
   • Selenium - How to take screenshot of ...  
   • How to take multiple screenshots in s...  
   • How to take locators(xpath) and check...  


I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected]


https://programmerworld.co/selenium/h...


Code:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;
import ru.yandex.qatools.ashot.coordinates.WebDriverCoordsProvider;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class compareScreenshot {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "Path of chromedriver exe\\chromedriver.exe");
ChromeOptions op = new ChromeOptions();
op.setBinary("Path of Chrome exe\\chrome.exe");
op.addArguments("--remote-allow-origins=*");
WebDriver driver = new ChromeDriver(op);
driver.get("https://programmerworld.co/");
BufferedImage expectedImage = ImageIO.read(new File("Path of expected image\\ExpectedImage.jpg"));

WebElement actualImageLocation = driver.findElement(By.xpath("//img[@class='custom-logo']"));

Screenshot scrShot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(500)).coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, actualImageLocation);
ImageIO.write(scrShot.getImage(), "jpg", new File("Path of actual image to be saved\\ActualImage.jpg"));

BufferedImage actualImage = ImageIO.read(new File("Path of actual image\\ActualImage.jpg"));

ImageDiffer imgdiff =new ImageDiffer();
ImageDiff diff = imgdiff.makeDiff(expectedImage, actualImage);
if(diff.hasDiff()) {
System.out.print("******Images are not same");
}
else
{
System.out.print("====Images are same");
}
}
}


--