WebDriver implements a method to capture a specific Web area

  • 2020-04-01 03:55:09
  • OfStack

As anyone who has ever used WebDriver knows, WebDriver can take a screenshot of a page in a browser. Such as:


public byte[] takeScreenshot() throws IOException {
 TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
 return takesScreenshot.getScreenshotAs(OutputType.BYTES);
}


The resulting image is the entire page. But sometimes we don't need the entire page, just some specific WebElement to avoid some distractions.

Although WebDriver itself does not provide such an API, we can do it by ourselves, and then crop it in the full-screen screenshot, as follows:


public BufferedImage createElementImage(WebElement webElement)
 throws IOException {
 //Gets the location and size of webElement.
 Point location = webElement.getLocation();
 Dimension size = webElement.getSize();
 //Create a full screen shot.
 BufferedImage originalImage =
  ImageIO.read(new ByteArrayInputStream(takeScreenshot()));
 //Intercept the subdiagram where webElement is located.
 BufferedImage croppedImage = originalImage.getSubimage(
  location.getX(),
  localtion.getY(),
  size.getWidth(),
  size.getHeight());
 return croppedImage;
}


Among them, ImageIO and BufferedImage are respectively from javax.imageio and java.awt.image.

This method is a good way to reduce the size of the screenshot and avoid some uncertainties (such as the date, time, etc.). It is a good way to save screenshots during testing.

Note: if the web page under test contains an iframe, the position of the WebElement needs to be calculated in a more complex way, see:


Related articles: