Capturing screen shots of browsers with Selenium and Cloud Testing – Part 2

 

 

In Part 1 of this article, we covered the basics of capturing screenshots with Selenium using the captureScreenshot() and captureEntirePageScreenshot() methods. In this part, we cover the use of the Java Robot.

Java Robot

The Java Robot, part of the AWT (Abstract Windowing Toolkit) allows developers to interact with the GUI in an automated manner, sending keyboard comands, moving the mouse, clicking buttons, and most importantly for us, taking a screenshot.

Taking a screenshot with the Robot

In the example below, we create a bufferedImage object which contains a full screenshot, and then write it out as a PNG.


import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.event.KeyEvent;
import java.io.File;
...
BufferedImage bufferedImage;
final Rectangle captureSize;
final Robot robot = new Robot();

// calculate what we want to capture
captureSize =
    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
//capture image
 bufferedImage = robot.createScreenCapture(captureSize);
// write the image out to a file
ImageIO.write(bufferedImage, "png", new File("screenshot.png"));

This is very similar to the captureScreenshot() command in Selenium, in that it is a direct screenshot of the OS window, taskbar and all:

java_robot_screenshot

Scrolling the window with the Robot

If we want to see what is further down the page, we can ask the Robot to press the PAGE DOWN key for us.

robot.keyPress(KeyEvent.VK_PAGE_DOWN);

Once we have pressed the PAGE DOWN key, we can take another screenshot using the Robot, as we did in first part. We then end up with the following:

java_robot_screenshot2

If you want to move up or down using the UP and DOWN keys, rather than a page at a time, you can use the following commands.

robot.keyPress(KeyEvent.VK_DOWN);

or

robot.keyPress(KeyEvent.VK_UP);

Image manipulation

If you want to snip off the taskbar, title bars, scroll bars this can easily be done using methods of the bufferedImage class before writing out the image.

Multiple screenshot images can also be stitched together to create a larger image – this is performed in the Cloud Testing service, and will be covered in future articles.

See also

Did you enjoy this post? Why not subscribe to our feed and get articles like this delivered automatically to your feed reader.

Comments
Leave a comment

(required)

(required)