Take screenshots

Screenshot of page

<code lang="java">
  public void takeScreenshot() throws IOException {
    File scrFile = ((TakesScreenshot) driver)
    String fileName = UUID.randomUUID().toString();
    File targetFile = new File("target/screenshots/" + fileName
        + ".jpg");
    FileUtils.copyFile(scrFile, targetFile);

Screenshot of WebElement

<code lang="java">
package book.chapter05;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
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.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;

public class TakeElementScreenshot {
  private final String screenshotFolder = "target/screenshots/";
  protected WebDriver driver;

  public TakeElementScreenshot(WebDriver driver) {
    this.driver = driver;

  public void shoot(WebElement element) throws IOException {
    try {
      driver = new Augmenter().augment(driver);
    } catch (Exception ignored) {
    File screen = ((TakesScreenshot) driver)
    Point p = element.getLocation();
    int width = element.getSize().getWidth();
    int height = element.getSize().getHeight();
    Rectangle rect = new Rectangle(width, height);
    BufferedImage img = null;
    img = ImageIO.read(screen);
    BufferedImage dest = img.getSubimage(p.getX(), p.getY(),
        rect.width, rect.height);
    ImageIO.write(dest, "png", screen);
    FileUtils.copyFile(screen, new File(screenshotFolder
        + System.nanoTime() + ".png"));

How to use it

<code lang="java">
package book.chapter05;

import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;

import book.chapter09.tests.DriverBase;

public class ShootElement extends DriverBase {

  public void takeScreenshotOfElement() throws IOException {
    WebElement element = driver.findElement(By.name("q"));

    // takescreenshot of element
    TakeElementScreenshot screenshot = new TakeElementScreenshot(

    System.out.println("Page title is: " + driver.getTitle());

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.