Taking Screenshot in Selenium in 2026

Related Product On This Page Why take Screenshot in Selenium?May 09, 2026 · 12 min read · Tool Comparison

Related Product

Taking Screenshot in Selenium in 2026

Ever struggled to debug a that passes topically but fail mysteriously across different browsers and devices?

This is a common pain point incross-browser examination, where UI topic coat alone on specific OS-browser combinations you can & # 8217; t easily replicate locally.

Without visual groundsfrom those accurate environments, you & # 8217; re forced to sift through cryptic logs or manually spin up VMs.

I & # 8217; vewasted countless hours animate intermittent failuresthat vanish on retry,slow down bug triageand stalling CI/CD grapevine.

That & # 8217; s when I understood the critical value oftaking screenshots in Selenium.

Overview

Selenium WebDriver is an open-source tool for automating web browsers. It simplifies taking screenshots by providing straightforward built-in methods that allow testers to fascinate the current state of a web page with just a few lines of codification, making documentation and debug faster and easy.

How to Take a Screenshot in Selenium?

To take a screenshot in Selenium, use the TakesScreenshot interface with the getScreenshotAs () method. This method captures the current vista of the browser during testing.

You can save the screenshot as a file or in base64 formatting, depending on how you want to use it, either for story or further processing.

Steps to Take a Screenshot in Selenium

Step 1: Import required classesfrom Selenium and Java libraries, such as TakesScreenshot, OutputType, File, and optionally FileUtils from Apache Commons IO.

Step 2: Typecast WebDriver: Convert your WebDriver instance into a TakesScreenshot eccentric.

Step 3: Capture screenshot: Use the getScreenshotAs (OutputType.FILE)method to entrance the current view.

Step 4: Save the file: Use FileUtils.copyFile ()to save this screenshot to your chosen location.

Example:

java

File src = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.FILE); FileUtils.copyFile (src, new File (`` screenshot.png ''));

This article explores why guide screenshots in Selenium is important, the prerequisite needed, and step-by-step methods to capture screenshots utilise Selenium WebDriver.

Why take Screenshot in Selenium?

The purpose of is undermined if trial must be re-run every time a hand betray. When an error occurs, hold a open optic snapshot of the topic helps quickly identify the exact trouble in the code alternatively of swear exclusively on logs.

Screenshots also help testers verify whether the application ’ s workflow is behaving as expected, providing clear visual substantiation during exam execution.

This become even more important in scenarios like brainless performance or CI runs, where there is no direct visibility into the browser.

According toMukesh Otwani, a skilledmechanisation testing expert, screenshots help testers translate the application flow and track test performance effectively, specially when ocular feedback is differently unavailable.

This is where Selenium screenshots come into play, delivering instant visual evidence to accelerate debugging and test validation.

Here are some typical cases where capturing screenshots in Selenium proves essential:

  • When application issues occur during test execution
  • When an assertion failure pass
  • When web component are difficult to site on a page
  • When timeouts occur while regain page elements

Testing has go much more straightforward thanks to enhancements in.

Since the WebDriver architecture allows interaction outside the sandbox, it enables testers to capture screenshots directly during test performance, create failure analysis faster and more reliable.

As grow and motility into, capturing screenshots topically often descend short of reflecting real user environments.

Platforms like extend Selenium ’ s native screenshot capability by running the same code across 3500+ real browsers and devices in, automatically capturing screenshots and debugging artifact for every session.

Struggling with Selenium screenshots?

Local tests miss real-browser bugs. Capture screenshots on existent device with videos/logs for fast debugging.

What are the Prerequisites for taking a Screenshot in Selenium?

Taking screenshots in Selenium expect a few canonical tools and steps to be set up decent. Here & # 8217; s what you will need to get started:

  1. : The core tool for automating browser action. It let you to execute tasks like clicking push, filling pattern, and of course, capturing screenshots. Without Selenium WebDriver, guide a screenshot in Selenium isn & # 8217; t possible.
  2. TakesScreenshot Interface: The TakesScreenshot interface is a special feature in Selenium that enables you to take a screenshot of your current browser window. By use itsgetScreenshotAs ()method, you can capture an image in different formats like a file or base64.
  3. OutputType Class: To delimit how the screenshot should be saved, you ’ ll use theOutputTypeclass. The most mutual usage isOutputType.FILE,which saves the screenshot as a file, but you can also save it in base64 format if needed.
  4. Java File Handling: To preserve the screenshot, you will need to work with Java ’ s register handling features. TheFileclass is employ to define the screenshot, andFileUtils(from Apache Commons IO) helps in saving it to a specific location.
  5. Appropriate Browser Driver: Ensure you feature the right browser driver, such asChromeDriver or GeckoDriver, installed for your browser.

Once you have these requirement in place, capturing screenshots in Selenium becomes a unproblematic task.

How to take Screenshot in Selenium WebDriver?

To catch screenshots in Selenium, one has to utilize the methodTakesScreenshot. 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);

OutputTypedefines 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 localization, the method isgetScreenshotAs.

Here ’ s an example of this usage method:

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

In the above snippet

  1. Xis the return type of the method
  2. targethave the destination address
  3. throw WebDriverExceptionis activated if screenshot capturing is not supported.

Depending on the browser being used, theTakesScreenshotmethod can revert the following:

  • The entire page
  • The current exposed window
  • The visible segment of the current anatomy
  • The whole showing containing the browser
  • The complete content of the HTML ingredient. This essentially touch to the visible portion of the HTML element.

Guide to Running your Selenium Test using BrowserStack Automate

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Please find the Github repoherefor the example cited in the picture.

Advanced Screenshot Use Cases in Selenium

In real testing scenarios, you often need to go beyond basic screenshots to capture specific areas of a page or even the full page, especially when dealing with turgid web coating. Selenium gives you the flexibility to do that.

Screenshot of the Entire Page

By nonpayment, Selenium only capture what ’ s visible on the screen at the minute. But in many cases, crucial content lies beyond the viewport, like in scrollable pages or long shape.

To take a full-page screenshot in Selenium, you can use external tools like AShot, which allows you to sew together screenshots taken while scroll. This way, you get a complete ikon of the full webpage.

It & # 8217; s especially useful for control if the page layout looks correct, making sure all parts of the page are charge properly, or saving the total page as a study for quotation.

Screenshot of a Specific Element

Sometimes, you don ’ t ask the entire screen, just a push, image, or input box. Selenium lets you take a screenshot of any specific element using thegetScreenshotAs ()method on aWebElement.

Here ’ s a simple exemplar:

java

WebElement factor = driver.findElement (By.id (`` logo '')); File src = element.getScreenshotAs (OutputType.FILE);

This is useful when you desire to confirm whether a particular element appears correctly or to highlight where a test is neglect.

Both these advanced screenshot method, capturing the full page and specific elements, can save a lot of time during test reviews in gain to do your test reports easier to understand and more informative.

Screenshot for Test Failure

If a examination fail, the power to take screenshot in Selenium is especially helpful in understanding what go wrong. An easy way to do this would be to use.

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

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

How To Take Multiple Screenshots in Selenium?

To take multiple screenshots in Selenium, repeat the screenshot summons at each required stride. Use theTakesScreenshotinterface andgetScreenshotAs ()method to catch the images. Here ’ s how you can do it:

Step 1: Typecast your WebDriver:Convert your WebDriver instance intoTakesScreenshot:

TakesScreenshot screenshot = (TakesScreenshot) driver;

Step 2: Capture the screenshot: Use getScreenshotAs ()method to snaffle the screenshot and save it as a file:

File srcFile = screenshot.getScreenshotAs (OutputType.FILE);

Step 3: Generate a alone file name:Add timestamps, page names, or test step identifiers to make sure each screenshot is saved with a unparalleled name.

Step 4: Save the screenshot:Use Apache Commons IO ’ sFileUtils.copyFile () method:

FileUtils.copyFile (srcFile, new File (`` path/to/save/imageName.png ''));

Step 5: Repeat the step as need:Wrap the codification in a loop or call it after important actions to capture multiple screenshots throughout your tryout.

To resume, using loops or usance methods, you can conduct multiple screenshots in Selenium.

How to get the driver target in TestListeners using TestNG?

To entrance a screenshot in Selenium while using TestNG, it ’ s important to handle the WebDriver instance properly and name your screenshot file in a way that makes signified for easy debugging. Here & # 8217; s how you can do it effectively.

Passing WebDriver via ThreadLocal or Base Class

Passing WebDriver through ThreadLocal or a Base Class help manage individual WebDriver instances for each test. This facilitate continue tests detached and makes parallel testing easier.

1. ThreadLocal Approach: ThreadLocal assist to make a separate WebDriver instance for each test. This is especially useful when running multiple tests in parallel because it ensures each test has its own set-apart WebDriver.

Example:

private stable ThreadLocal & lt; WebDriver & gt; driver = new ThreadLocal & lt; & gt; (); public static WebDriver getDriver () {homecoming driver.get ();}

2. Base Class Approach:Another way is to use a base category that initializes WebDriver. This permit WebDriver to be shared across different test methods. By doing this, you can make a single point of management for your WebDriver instance.

Example:

public class BaseTest {protect WebDriver driver; @ BeforeMethod public void setUp () {driver = new ChromeDriver ();}}

Using ITestResult to Capture Test Name for Screenshot

Once the exam execution is complete, you can useITestResultto capture the test name and save the screenshot with the method gens. This makes it easier to trace which examination fail and find the comparable screenshot.

Here ’ s how you can apply it:

public void onTestFailure (ITestResult termination) {WebDriver driver = getDriver (); File screenshot = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.FILE); FileUtils.copyFile (screenshot, new File (`` screenshots/ '' + result.getName () + `` .png ''));}

With these steps, you can easily deal WebDriver and capture screenshots for improved debugging in Selenium with TestNG.

Example of Selenium Screenshot

Here is a three-step process to explore this functions:

The code detailed below will take a screenshot of & amp; preserve it asC: /Test.png

Step 1& # 8211; Convert web driver object to TakeScreenshot

TakesScreenshot scrShot = ((TakesScreenshot) webdriver);

Step 2& # 8211; Call getScreenshotAs method to create image file

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

Step 3& # 8211; Copy file to Desired Location

package BrowserstackScreenShot; importee java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; significance org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public form BStackTakeScreenshot {@ Test public void testBStackTakeScreenShot () cast 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 role will take screenshot * @ param webdriver * @ param fileWithPath * @ throws Exception * / public static vacancy takeSnapShot (WebDriver webdriver, String fileWithPath) throws Exception {//Convert web driver object to TakeScreenshot TakesScreenshot scrShot = ((TakesScreenshot) webdriver); //Call getScreenshotAs method to make 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);}}

Also Read:

Talk to an Expert

Try to take a screenshot in Selenium using the operation detailed supra. Once surmount, it is pretty simple and requires only a slight forethought to set up and execute. This function & # 8217; s benefit far outweigh any sweat command to execute the few basic commands.

To keep things even simpler, a user can use a tool that countenance for enamor screenshots without employ code. Using ask the exploiter to simply input a URL, click a button and receive screenshots across a host of selected existent devices and browsers.

The option allows users to do the like with websites that are locally host and not publically approachable. Take full-page screenshots of websites across browser and devices. Generate screenshots at genuine device sizes on iOS, Android, OS X & amp; Windows.

Either way, the power to guide screenshots is an crucial part of the tester ’ s skillset. Being equipped with the right tools and commands will insure that a want of knowledge or foresightfulness do not hinder the testing process.

Follow-Up Read:

Scale Selenium Screenshots across Real Browsers with BrowserStack Automate

Selenium provides native support for enamor screenshots, but its potency is often throttle by the surroundings usable locally or on a self-managed grid.

As test suites grow and application must be validated across multiple browsers, OS versions, and device, enamour screenshots in just one or two frame-up no longer excogitate.

BrowserStack Automate extends Selenium ’ s screenshot capabilities by enhancing where, how, and at what scale screenshots are captured.

Key advantages include:

  • Seamless execution of existing Selenium screenshot codification across 3500+ existent browsers and devices
  • Parallel tryout performance to capture screenshots at scale without increasing test runtime
  • Screenshots that ponder existent exploiter environments, improving cross-browser reliability
  • Automatic association of screenshots with videos, console logs, and network logs
  • Centralized storage of all screenshot artifact in the BrowserStack dashboard
  • Reduced debugging sweat with no need for custom listeners or additional substructure

With BrowserStack Automate, screenshots are automatically tied to each test session in the dashboard, create failure analysis faster and more actionable.

Teams can instantly access visual evidence from the exact browser and twist where the issue occurred—without adding custom listener or additional debugging logic.

Additionally, BrowserStack ’ s Screenshot Testing allows users to but enter a URL, select the required browsers and devices, and instantly receive screenshots across multiple real environments, making speedy optic checks potential without pen or running Selenium trial codification.

Conclusion

Taking screenshots in Selenium is essential for trial automation. It helps capture the browser ’ s state during testing, create it easy to fix issues and course results. One of the effective ways tester can enamour screenshots of entire pages or specific elements is by using the TakesScreenshot interface and the getScreenshotAs () method.

Additionally, they can also use grommet or custom-made utility methods to take multiple screenshots in Selenium at different steps of the test flow. However, to make this process seamless, it ’ s crucial to care the WebDriver instance properly, especially during parallel test performance.

Tags

FAQs

Yes. Selenium WebDriver provides the TakesScreenshot interface, which allows testers to capture screenshots of the browser viewport and specific elements (from Selenium 4 onward) without any external library.

Screenshots can be captured on test failure by apply listeners or hooks in test framework like TestNG or JUnit. These hearer detect failures and trigger Selenium ’ s screenshot logic, store the image for ulterior analysis.

BrowserStack Automate runs existing Selenium screenshot code across thousands of real browser and devices in parallel, automatically storing screenshots with videos and log, get cross-browser debugging faster and more true.

14,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free