Home Guide How to take Screenshots in Selenium?

How to take Screenshots in Selenium?

Shreya Bose, Technical Content Writer at BrowserStack -

Why take screenshots in the first place?

Automated testing has become a significant part of the entire software testing lifecycle. The ability to execute a script and get results without interference or monitoring has resulted in significantly higher levels of efficiency in much shorter timelines – something every agile team needs.

However, the whole point of automated testing is defeated if one has to re-run an entire test every time a script fails. If something goes wrong, it helps not just to have the bug pointed out in the code, but also have some visual representation of the exact anomaly. Similarly, a tester has to check if the flow of the application is as intended. Once again, visual representation helps in this case.

This is where Selenium screenshots come in.

Here are some typical cases in which Selenium screenshots would be required:

  • When application issues occur
  • When an assertion failure occurs
  • When there is some difficulty in finding web elements on a page
  • Where there is a Timeout in finding web elements on a web page

Thanks to certain new functionalities incorporated in Selenium WebDriver, testing has become much simpler. Since the WebDriver architecture allows a user to interact outside the Javascript sandbox, it is possible, among other things, to take screenshots in Selenium.

How does a user take a screenshot in Selenium?

In order to capture a screenshot in Selenium, one has to utilize the method TakesScreenshot. This notifies WebDrive that it should take a screenshot in Selenium and store it.

Syntax:

File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String screenshotBase64 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);

In the above snippet, OutputType defines the output type for the required screenshot.

If the user intends to take a Selenium screenshot and store it in a designated location, the method to use is getScreenshotAs.

Here’s an example of this method in usage:

X getScreenshotAs(OutputType(X). target) throws WebDriverException

In the above snippet

  1. X is the return type of the method
  2. target holds the destination address
  3. throws WebDriverException is activated if screenshot capturing is not supported.

Depending on the browser being used, the TakesScreenshot method can return the following:

  • The entire page
  • The current open window
  • The visible segment of the current frame
  • The whole display containing the browser
  • The complete content of the HTML element. This essentially refers to the visible portion of the HTML element.

Test Screenshots in Selenium for Free

Screenshot for test failure

If a test fails, the ability to take screenshots in Selenium is especially helpful to understand what went wrong. An easy way to do this would be to use TestNG annotations.

Here are the steps to capture a screenshot in selenium in this case:

  • Create a class. Implement TestNG ‘ITestListener‘.
  • Call the method ‘onTestFailure’.
  • Add the code to take a screenshot with this method.
  • Get the Test method name and take a screenshot with the test name. Then place it in the desired destination folder.

How to get the driver object in TestListeners using TestNG?

Taking Selenium screenshots requires a user to have a driver object. In order to do so, one has to get the driver from ITestContext which, in turn, must be configured in the base setup. This makes it easy to create a driver instance and proceed accordingly.

Example of Selenium Screenshot

Let’s explore this function with a three-step process –

The code detailed below will take a screenshot of https://www.browserstack.com & save it as C:/Test.png

Step #1 – Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Step #2 – Call getScreenshotAs method to create image file

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

Step #3 – Copy file to Desired Location

package BrowserstackScreenShot;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class BStackTakeScreenshot {
@Test
public void testBStackTakeScreenShot() throws Exception{

WebDriver driver ;
System.setProperty("webdriver.firefox.marionette","c:\\geckodriver.exe");
driver = new FirefoxDriver();
//goto url
driver.get("https://www.browserstack.com");
//Call take screenshot function
this.takeSnapShot(driver, "c://test.png") ; 
}
/**
* This function will take screenshot
* @param webdriver
* @param fileWithPath
* @throws Exception
*/
public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{
//Convert web driver object to TakeScreenshot
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
//Call getScreenshotAs method to create image file
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
//Move image file to new destination
File DestFile=new File(fileWithPath);
//Copy file at destination
FileUtils.copyFile(SrcFile, DestFile);
}
}

Try to take a screenshot in Selenium using the process detailed above. Once mastered, it is quite simple and requires only a little forethought to set up and execute. The benefits this function provides far outweigh any effort required to execute the few basic commands.

To keep things even simpler, a user can use a tool that allows for capturing screenshots without using code. A tool such as BrowserStack’s screenshot generator, requires the user to simply input a URL, click a button and receive screenshots across a host of selected real devices and browsers. The Local Testing option allows users to do the same with websites that are locally hosted and not publically accessible.

Try Screenshot Tool for Free

BrowserStack Browser Screenshot Tool

BrowserStack Screenshots Tool Dashboard

Either way, the ability to take screenshots is an important part of the tester’s skillset. Being equipped with the right tools and commands will go a long way towards ensuring that the testing process is not hindered by a lack of knowledge or foresight.

BrowserStack Logo Run Selenium Tests on 2000+ Browsers & Devices Get Started Free