Home > OS >  How can I compare two photos in java selenium?
How can I compare two photos in java selenium?

Time:05-18

i have no idea how can I compare two photo adress, i tried to search answears for hours and still found nothing. So i came here and im looking for answear

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class FirstAutomatedTest {
    
    private WebDriver driver;

    @BeforeMethod
    public void beforeTest() {
        System.setProperty("webdriver.chrome.driver", "C:/drivers/chromedriver.exe");
        driver = new ChromeDriver();
    }
    @Test
    public void myFirstTest() {
        driver.navigate().to("http://michalmarek.great-site.net/tytul/?i=2");
        driver.findElements(By.tagName("img"));
        driver.navigate().refresh();
        driver.findElements(By.tagName("img"));
    }
    @AfterMethod
    public void afterTest() {
    }
}```

   

CodePudding user response:

I assume you are trying to compare two image sources not images. If that is your case then you can do like below,

Code:

driver.navigate().to("https://www.stackoverflow.com");
String orginalImage = driver.findElement(By.xpath("//div[@style='clip-path:url(#curve)']/div/img"))
        .getAttribute("src");
System.out.println("Original image source: "   orginalImage);
driver.navigate().refresh();
String refreshedImage = driver.findElement(By.xpath("//div[@style='clip-path:url(#curve)']/div/img"))
        .getAttribute("src");
System.out.println("Refreshed image source: "   refreshedImage);
Assert.assertEquals(orginalImage, refreshedImage, "Both image sources are not same.");

Output:

Original image source: https://cdn.sstatic.net/Img/home/illo-code.svg?v=b7ee00fff9d8
Refreshed image source: https://cdn.sstatic.net/Img/home/illo-code.svg?v=b7ee00fff9d8

If you want to compare images pixel by pixel then you need try these,

CodePudding user response:

Welcome to SO.

According to your comment, you want to check all image source location should be different when the page refresh.

To be doing that, we need to store first image locations and compare this list after refresh.

@Test
public void myFirstTest() {
    driver.navigate().to("http://michalmarek.great-site.net/tytul/?i=2");
    List<String> firstImages = driver.findElements(By.tagName("img"))
            .stream()
            .map(e -> e.getAttribute("src"))
            .collect(Collectors.toList());
    driver.navigate().refresh();
    List<String> lastImages = driver.findElements(By.tagName("img"))
            .stream()
            .map(e -> e.getAttribute("src"))
            .collect(Collectors.toList());
    Assertions.assertTrue(Collections.disjoint(firstImages, lastImages));
}

Collections.disjoint Returns true if the two specified collections have no elements in common.

  • Related