Selenium Webdriver Tutorials

How to capture Screenshot in Selenium Webdriver using Java

The basic rule of testing is to always take screenshot to base your claim. You can take screenshots at any stage of the test, but mostly, it is used for when a test fails and taking screenshots helps the analysis so we can see what went wrong during a test failure. The defects you log should always have a screenshot attached to it. However, it is not necessary that screenshot should be taken only when you encounter a situation where expected result does not match the actual result. Screenshot are also taken as a proof that things are working fine. In this tutorial we will learn how to capture Screenshot in Selenium Webdriver using Java, i.e. TakesScreenshot class.

Capture Screenshot in Selenium Webdriver
“International Women’s Day” Google Doodle

Capture Screenshot in Selenium Webdriver

Selenium Webdriver provides “TakesScreenShot” interface and “getScreenshotAs()” method for capturing the screenshots at any moment during the test execution. 

And then we can save this screenshot at any location in our local machine using “copyFile()” function provided by Java “FileUtils” class from the org.apache.commons.io.FileUtils.

The below code will open www.Google.com URL in Chrome browser and will try to find an element by using id = “testing”. Since it couldn’t find the element, an exception will be thrown and then screenshot will be captured of the current page & saved in specified Desktop folder location.

Open Browser and Website

The code below will open the Chrome browser & then Google.com URL.

Try block

The ‘try block’ will try to identify an element using id = “testing”, which is NOT present on the webpage. Hence an exception will be thrown.

Catch block

This is the primary code for this article. Once an exception is thrown by ‘try’ block, catch block will be executed. The screenshot is captured as a ‘FILE’ and stored in variable scrFile. After capturing the screenshot, the code saves it to the specified folder path with name as ‘screenshot.png’ using copyFile() function of the FileUtils class.

Pro Tip: Since we need to capture screenshots during our complete testing, repeating the same code in every script is NOT recommended. Instead create a small method (say captureScreenshot) which captures screenshot and then call this method from the scripts.

With this we come to the end of this tutorial – How to capture Screenshot in Selenium Webdriver using Java. Do share this post with your friends. You can subscribe to ‘Software Testing Studio’ via Email OR follow us @ Facebook, LinkedIn, Twitter or Google+ for regular updates on new posts, tutorials, tips & tricks. Do leave us a comment/feedback and help us improve.

Happy Testing!!

Leave a Reply

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