Como fazer uma captura de tela Selenium webdriver
⚡ Resumo Inteligente
Tirar captura de tela Selenium O WebDriver explica como capturar evidências visuais para depuração e regressão visual, abordando os métodos TakesScreenshot, captura de página inteira, captura de elementos e AShot.

Captura de tela em Selenium
A Captura de tela em Selenium Driver da Web é usado para análise de bugs. Selenium WebDriver does not take screenshots on its own. To capture one, you cast the driver to the TakesScreenshot interface and call getScreenshotAs(). Test frameworks such as TestNG can call this automatically, for example from a listener when a test fails.
Como fazer uma captura de tela Selenium
Aqui está um processo passo a passo sobre como capturar uma captura de tela no Selenium WebDriver
Passo 1) Converter o objeto do driver da web em TakeScreenshot
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
Passo 2) Chame o método getScreenshotAs para criar o arquivo de imagem.
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Etapa 3) Copie o arquivo para o local desejado.
Exemplo: Neste exemplo, faremos uma captura de tela de https://demo.guru99.com/V4/ e a salvaremos como C:/Test.png
Aqui está o código da captura de tela em selênio:
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("https://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);
}
}
OBSERVAÇÃO: Selenium a versão 3.9.0 e superior não fornece Apache Commons IO JAR. Você pode simplesmente baixá-los aqui. e chame-os em seu projeto
O que é API Ashot?
Ashot é um utilitário de terceiros da Yandex suportado pela Selenium WebDriver para capturar as capturas de tela. Ele faz uma captura de tela de um WebElement individual, bem como uma captura de tela de página inteira de uma página, o que é mais significativo do que o tamanho da tela.
Como baixar e configurar a API Ashot?
Existem dois métodos para configurar a API Ashot
- Usando Maven
- Manualmente sem usar nenhuma ferramenta
Para configurar através do Maven:
- Acesse https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
- Clique na versão mais recente, por enquanto. É 1.5.4
- Copie o código de dependência e adicione ao seu arquivo pom.xml
- Salve o arquivo e o Maven adicionará o jar ao seu caminho de construção
- E agora você está pronto!!!
Para configurar manualmente sem qualquer ferramenta de dependência
- Acesse https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
- Clique na versão mais recente, por enquanto. É 1.5.4
- Clique no jar, baixe e salve em sua máquina
- Adicione o arquivo jar no caminho de construção:
- In Eclipse, clique com o botão direito no projeto -> vá para propriedades -> Caminho de construção -> Bibliotecas -> Adicionar jars externos
- Selecione o arquivo jar
- Aplicar e fechar
Capture captura de tela de página inteira com API AShot
Passo 1) Crie um objeto Ashot e chame o método takeScreenshot() se você quiser apenas a captura de tela da página no tamanho da tela.
Screenshot screenshot = new Ashot().takeScreenshot(driver);
Mas se você quiser uma captura de tela da página maior que o tamanho da tela, chame o método shootingStrategy() antes de chamar o método takeScreenshot() para configurar a política. Em seguida, chame um método takeScreenshot() passando o webdriver, por exemplo,
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
Aqui 1000 é rolado em milissegundos, portanto, para fazer uma captura de tela, o programa rolará a cada 1000 ms.
Passo 2): Agora, obtenha a imagem da captura de tela e salve-a no arquivo. Você pode especificar o tipo de arquivo como jpg, png, etc.
ImageIO.write(screenshot.getImage(), "jpg", new File(".\\screenshot\\fullimage.jpg"));
Tirar uma captura de tela de página inteira de uma página maior que o tamanho da tela.
Exemplo: Aqui está um exemplo de como capturar uma imagem da página inteira de https://demo.guru99.com/test/guru99home/ e salvá-la no arquivo "screenshot.jpg".
Devido ao uso da classe ShootingStrategy da API Ashot, seremos capazes de capturar uma imagem completa de uma página maior que o tamanho da tela.
Aqui está o código da captura de tela no programa Selenium:
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("https://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"));
}
}
Tirar uma captura de tela de um elemento específico da página
Exemplo: Aqui está um exemplo de captura de tela de um elemento. Guru 99 logotipo em https://demo.guru99.com/test/guru99home/ página e salve como arquivo "ElementScreenshot.jpg".
Aqui está o código da captura de tela em selênio:
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("https://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"));
}
}
Comparação de imagens 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("https://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()) {
System.out.println("Images are different");
} else {
System.out.println("Images are same");
}
driver.quit();
}
}



