The java.awt.Robot class is mainly useful to perform native actions where keyword and mouse actions to be performed. This actions are helpful for automation. If the current platform configuration does not allow input controls, an AWTException will be thrown when using the java.awt.Robot class. In this post we will java.util.Robot class for capturing the screenshots. The method createScreenCapture(Rectangle screenRect) is available in java.awt.Robot class which helps to create an image containing pixels read from the screen.The java.awt.Rectangle object to be passed as an parameter for capturing the screenshot. To create an Rectangle object the java.awt.Dimension[Height*Width] object to be passed as an parameter.
API Classes and Methods useful to capture the Screenshot as follows:
- Robot Class Object
- Rectangle Class Object
- Dimension Class Object- Input Parameters Height * Width
Selenium WebDriver Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.awt.AWTException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.openqa.selenium.firefox.FirefoxDriver; public class CaptureScreenshotRobot { public void captureScreenshot(String testcase_testStep_ID) throws IOException, AWTException { // Instantiate the Robot Class Robot robotObject = new Robot(); // Fetch the Details of the Screen Size Rectangle screenSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); // Take the Snapshot of the Screen BufferedImage tmp = robotObject.createScreenCapture(screenSize); // Provide the destination details to copy the screenshot String path=testcase_testStep_ID+System.currentTimeMillis()+".jpg"; // To copy source image in to destination path ImageIO.write(tmp, "jpg",new File(path)); } public static void main(String[] args) throws IOException, AWTException { System.setProperty("webdriver.gecko.driver", "geckodriver.exe"); FirefoxDriver driver = new FirefoxDriver(); driver.get("http://www.total-qa.com"); new CaptureScreenshotRobot().captureScreenshot("TC_001_TS_002"); } } |
Output:
The full screen is captured as screenshot which is the expected outcome as shown below: