How to take Screenshot in Selenium WebDriver (With Example)
By Shreya Bose, Community Contributor - February 13, 2023
Automated testing has become a significant part of every product’s software testing strategies. 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.
Why take screenshot in Selenium?
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 to have the bug pointed out in the code and to have some visual representation of the exact anomaly. Similarly, a tester must check if the application’s flow is as intended. Once again, visual representation through screenshot testing helps in this case.
This is where Selenium screenshots come into play.
Here are some typical cases where its crucial to take screenshot in Selenium:
- 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
Testing has become much more straightforward thanks to certain new functionalities incorporated in Selenium WebDriver. Since the WebDriver architecture allows a user to interact outside the Javascript sandbox, it is possible, among other things, to take screenshot in Selenium.
How to take screenshot in Selenium WebDriver?
To capture screenshots in Selenium, one has to utilize the method TakesScreenshot. This notifies WebDriver 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);
OutputType defines the output type for the required screenshot in the above snippet.
If the user intends to take screenshot in Selenium and store it in a designated location, the method is getScreenshotAs.
Here’s an example of this usage method:
X getScreenshotAs(OutputType(X). target) throws WebDriverException
In the above snippet
- X is the return type of the method
- target holds the destination address
- 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.
Guide to Running your Selenium Test using BrowserStack Automate
Please find the Github repo here for the example cited in the video.
Screenshot for Test Failure
If a test fails, the ability to take screenshot in Selenium is especially helpful in understanding 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. 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.
Read More: All About TestNG Listeners
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 pretty simple and requires only a little forethought to set up and execute. This function’s benefits 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. Using BrowserStack’s screenshot testing 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. Take full-page screenshots of websites across browsers and devices. Generate screenshots at actual device sizes on iOS, Android, OS X & Windows.
Try Screenshot Testing for Free
Either way, the ability to take screenshots is an essential part of the tester’s skillset. Being equipped with the right tools and commands will ensure that a lack of knowledge or foresight does not hinder the testing process.
Follow-Up Read: How to take Screenshots using Python and Selenium