Cómo tomar una captura de pantalla en Selenium WebDriver

Captura de pantalla en Selenium Webdriver

UNA. Captura de pantalla en Selenium Webdriver utilizado para el análisis de errores. Un controlador web de selenio puede tomar capturas de pantalla automáticamente durante la ejecución. Pero si los usuarios necesitan tomar una captura de pantalla por su cuenta, deben usar el modo TakeScreenshot, que notifica al WebDrive que tome la foto y la almacene en Selenium.

En este tutorial, aprenderá,

Captura de pantalla usando Selenium WebDriver

La captura de pantalla en selenio es un proceso de 3 pasos

Paso 1) Convierta el objeto del controlador web en TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Paso 2) Llame al modo getScreenshotAs para crear un archivo de imagen

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

Paso 3) Copiar un archivo en una ubicación deseada

Ejemplo: En este ejemplo, tomaremos una captura de pantalla. http://demo.guru99.com/V4/ & guárdelo como C: /Test.png


package Guru99TakeScreenshot;

import java.io.File;

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.annotations.Test;

public class Guru99TakeScreenshot {

    @Test

    public void testGuru99TakeScreenShot() throws Exception{

		WebDriver driver ;
    	System.setProperty("webdriver.gecko.driver","C:\geckodriver.exe");
    	driver = new FirefoxDriver();

        //goto url

        driver.get("http://demo.guru99.com/V4/");

        //Call take screenshot function

        this.takeSnapShot(driver, "c://test.png") ;     

    }

    /**

     * This function will take screenshot

     * @param webdriver

     * @param fileWithPath

     * @throws Exception

     */

    public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{

        //Convert web driver object to TakeScreenshot

        TakesScreenshot scrShot =((TakesScreenshot)webdriver);

        //Call getScreenshotAs method to create image file

                File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

            //Move image file to new destination

                File DestFile=new File(fileWithPath);

                //Copy file at destination

                FileUtils.copyFile(SrcFile, DestFile);

    }

}

NOTA: Selenium versión 3.9.0 y superior no proporciona Apache Commons IO JAR. Simplemente puede descargarlos aquí y llámalos en tu proyecto

¿Qué es Ashot API?

Ashot es una utilidad de terceros con Yandex respaldada por Selenium WebDriver para capturar las capturas de pantalla. Toma una imagen de un WebElement individual, así como una imagen de página completa de una página, que es más notable que el tamaño de la pantalla.

¿Cómo descargar y configurar la API de Ashot?

Hay dos métodos para configurar la API de Ashot

Para configurar a través de Maven:

Configuración manual sin herramienta de dependencia

  1. Ir https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
  2. Haga clic en la última versión, ahora. Es 1.5.4
  3. Haga clic en el frasco, descárguelo y guárdelo en su máquina
  1. Coloque el archivo jar en su ruta de construcción:
  2. En Eclipse, haga clic derecho en el proyecto -> vaya a propiedades -> Ruta de compilación -> Bibliotecas -> Agregar frascos externos
  3. Seleccione el archivo jar
  4. Aplicar y cerrar

Captura de pantalla Captura de pantalla de página completa con AShot API

Paso 1) Cree un objeto Ashot y llame a takeScreenshot () si desea la captura de pantalla para la página de tamaño de pantalla.

Screenshot screenshot = new Ashot().takeScreenshot(driver);

Pero si desea una imagen más grande de la página que el tamaño de la pantalla, llame al modo de disparo Estrategia () antes de llamar al modo de captura de pantalla () para configurar la política. Luego, llame al modo takeScreenshot () pasando por el controlador web, por ejemplo,

Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

Aquí el tiempo de desplazamiento es 1000 en milisegundos, por lo que para tomar una foto, el programa se desplazará cada 1000 ms.

Paso 2): Ahora, obtenga la imagen de la foto y escríbala en el archivo. Puede proporcionar el tipo de archivo como jpg, png, etc.


ImageIO.write(screenshot.getImage(), "jpg", new File(".\screenshot\fullimage.jpg"));

Hacer una captura de pantalla de página completa de una página que es más grande que el tamaño de la pantalla.

Ejemplo: Aquí hay un ejemplo de una captura de pantalla de página completa. http://demo.guru99.com/test/guru99home/ y guárdelo en «screenshot.jpg».

Al usar la clase ShootingStrategy de la API Ashot, podremos capturar una imagen completa de una página más grande que el tamaño de la pantalla. Aquí está el programa:


package Guru99;

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class TestScreenshotUsingAshot {

public static void main(String[] args) throws IOException {
	
System.setProperty("webdriver.chrome.driver", "c:\chromedriver.exe");
WebDriver driver  = new ChromeDriver();	

driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
		
Screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

ImageIO.write(screenshot.getImage(), "jpg", new File("c:\ElementScreenshot.jpg"));
	
	}

}

Tomar una foto de un aspecto particular de la página

Ejemplo: Aquí está el ejemplo de una foto de un elemento de un logotipo de Guru 99 capturado en http://demo.guru99.com/test/guru99home/ página y guardar en el archivo «ElementScreenshot.jpg». Aquí está el código:


package Guru99;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TestElementScreenshotUsingAshot {
public static void main(String[] args) throws IOException {
	
System.setProperty("webdriver.chrome.driver", "c:\chromedriver.exe");
WebDriver driver  = new ChromeDriver();	

driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
		
// Find the element to take a screenshot

WebElement element = driver.findElement(By.xpath ("//*[@id="site-name"]/a[1]/img"));

// Along with driver pass element also in takeScreenshot() method.

Screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver,element);

ImageIO.write(screenshot.getImage(), "jpg", new File("c:\ElementScreenshot.jpg"));
	}
}

Comparación de imágenes usando AShot


package Guru99;

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 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;

public class TestImageComaprison {

    public static void main(String[] args) throws IOException {

        System.setProperty("webdriver.chrome.driver", "C:\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://demo.guru99.com/test/guru99home/");

        // Find the element and take a screenshot

        WebElement logoElement = driver.findElement(By.xpath("//*[@id="site-name"]/a[1]/img"));
        Screenshot logoElementScreenshot = new AShot().takeScreenshot(driver, logoElemnent);

        // read the image to compare

        BufferedImage expectedImage = ImageIO.read(new File("C:\Guru99logo.png"));

        BufferedImage actualImage = logoElementScreenshot.getImage();

        // Create ImageDiffer object and call method makeDiff()

        ImageDiffer imgDiff = new ImageDiffer();
        ImageDiff diff = imgDiff.makeDiff(actualImage, expectedImage);

        if (diff.hasDiff() == true) {
            System.out.println("Images are same");

        } else {
            System.out.println("Images are different");
        }
        driver.quit();
    }
}

Resumen

Se puede hacer con contribuciones de Shradhdha Dave

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *