How To Take A Screenshot In Selenium WebDriver

Last updated on Jul 01,2021 32.2K Views

How To Take A Screenshot In Selenium WebDriver

edureka.co

Automation Testing has defined a new facet of modern day testing and it is here to stay. However, if the testing process fails, it would be highly inconvenient to re-test the entire script. This is where screenshots come in handy, as they help detect test failures instantly. Through the medium of this blog, we will learn how to take a screenshot in Selenium WebDriver. To learn more, check out the Selenium Training.

I’ll be discussing the following topics:

So, let’s get started, folks!

Screenshot in Selenium WebDriver: Why Screenshot is required in Automation testing?

Screenshots are desirable for bug analysis. Selenium can automatically take screenshots during execution. Suppose you write a test script to automate a web page, you would not keep monitoring to see if it’s working right every time. You would let the script do its job and you’d be occupied in some other work.

  • Screenshots help us in understanding the flow of application and checks if it is behaving accordingly.
  • You need to typecast WebDriver instance to TakesScreenshot.
  • It helps while you are performing cross-browsing testing as the user requires to view the reports of the execution
  • Tracking the execution would become much easy if you are working on a headless browser.
  • Screenshot of the tests that failed can also be easily captured.

Now, let us move ahead and learn how exactly you can take a screenshot in while testing an application.

Screenshot in Selenium WebDriver: How to capture Screenshot in Selenium?

To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways.

Syntax:

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

where OutputType defines the output type for a screenshot.

In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs

Let’s understand this in detail

For WebDriver extending TakesScreenshot method, this makes the best effort depending on the browser to return the following in a preferable order:

Syntax:

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

where

Test case failed

Selenium WebDriver has come up with some great new functionalities that make testing an application much easier. This is because the WebDriver architecture allows interaction outside of Javascript sandbox. One of the new useful functionality is being able to take screenshots from the WebDriver.

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. This can be done using TestNG annotations. 

To do this, first, I’ll need to

Now, the question is how to get the driver object in the TestListeners class using TestNG?

I’ll help you understand how easy it is to do that.

To take a screenshot in Selenium, we need to to have a driver object. Get the driver from the ITestContext which has to be set in the base setup where it is easy to create our driver instance.
Hope you guys are clear with this. Moving ahead, we’ll take a look at the demo where I will help you understand how simple it is to take a screenshot in Selenium.

I will be explaining two different programs here so that you get a proper idea about how to take a screenshot in Selenium.

First program deals with how to capture a screenshot of the test case run successfully. The second program helps you understand how to take a screenshot during the test failure.

Screenshot in Selenium WebDriver: Demo

The very first thing to do when you want to test a web application is to have the Selenium Jar files and the Java libraries. You can choose an IDE of your choice. I prefer working on the Eclipse IDE because it is user-friendly.

In this case, I will take a screenshot of our official webpage Edureka.co.

Refer to the below code:


import java.io.File;
import java.io.IOException;

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.chrome.ChromeDriver;

public class Screen {

public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:UsersNeha_VaidyaDesktopchromedriver_win32chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.edureka.co/");
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/Screen.png"));
System.out.println("the Screenshot is taken");
driver.quit();
}

}

The output for the above code is depicted below:

And the folder contains the image

Now, let us understand how to take a screenshot of the test failed

You can refer to this code:

BaseClass


package com.edureka;
import java.io.File;
import java.io.IOException;
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.chrome.ChromeDriver;
import org.testng.annotations.Listeners;

public class BaseClass {
public static WebDriver driver;

public static void initialization()
{
System.setProperty("webdriver.chrome.driver", "C:UsersNeha_VaidyaDesktopchromedriver_win32chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.edureka.co/");

}
public void failed()
{
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("/C:/Users/Neha_Vaidya/eclipse-workspace/Screens/"
+ "ScreenshotsTaken/tests.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}

}

DemoClass


package com.edureka;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(ListenersClass.class)
public class demo extends BaseClass{
@BeforeMethod
public void setUp() {
initialization();

}

@AfterMethod
public void tearDown()
{
driver.quit();
}

@Test
public void takeScreenshotTest()
{
Assert.assertEquals(true, false);
}
}

ListenersClass


package com.edureka;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class ListenersClass extends BaseClass implements ITestListener{

public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestFailure(ITestResult result) {
System.out.println("Failed Test");
failed();

}

public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub

}

public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub

}

public void onStart(ITestContext context) {
// TODO Auto-generated method stub

}

public void onFinish(ITestContext context) {
// TODO Auto-generated method stub

}

}

The output is depicted in this manner:

With this, we come to an end to this “How to take a screenshot in Selenium WebDriver” blog. I hope you guys enjoyed this article and understood how to run a test case. Got a question for us? Please mention it in the comments section of “How to take a screenshot in Selenium WebDriver” and we will get back to you.
If you wish to learn more about Selenium WebDriver and build a career in the same, then check out our Selenium Certification Course which comes with instructor-led live training and real-life project experience. This training will help you understand Selenium Testing in depth and help you achieve mastery over the subject.
Upcoming Batches For Selenium Certification Training Course
Course NameDateDetails
Selenium Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Selenium Certification Training Course

Class Starts on 20th May,2024

20th May

MON-FRI (Weekday Batch)
View Details
Selenium Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES