Taking Screenshot in Selenium in 2026
Related Product On This Page Why take Screenshot in Selenium?May 09, 2026 · 12 min read · Tool Comparison
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. 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 This article explores why guide screenshots in Selenium is important, the prerequisite needed, and step-by-step methods to capture screenshots utilise Selenium WebDriver. 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: 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. 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: Once you have these requirement in place, capturing screenshots in Selenium becomes a unproblematic task. 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: 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: In the above snippet Depending on the browser being used, theTakesScreenshotmethod can revert the following: 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. 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. 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. 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 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. 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: 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: Step 2: Capture the screenshot: Use getScreenshotAs ()method to snaffle the screenshot and save it as a 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: 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. 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 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: 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: 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: With these steps, you can easily deal WebDriver and capture screenshots for improved debugging in Selenium with TestNG. 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 Step 2& # 8211; Call getScreenshotAs method to create image file Step 3& # 8211; Copy file to Desired Location Also Read: 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: 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: 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. 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. 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. On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
Taking Screenshot in Selenium in 2026
Overview
File src = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.FILE); FileUtils.copyFile (src, new File (`` screenshot.png ''));
Why take Screenshot in Selenium?
Struggling with Selenium screenshots?
What are the Prerequisites for taking a Screenshot in Selenium?
How to take Screenshot in Selenium WebDriver?
File file = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.FILE); String screenshotBase64 = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.BASE64);
X getScreenshotAs (OutputType (X). mark) throws WebDriverException
Advanced Screenshot Use Cases in Selenium
Screenshot of the Entire Page
Screenshot of a Specific Element
WebElement factor = driver.findElement (By.id (`` logo '')); File src = element.getScreenshotAs (OutputType.FILE);
Screenshot for Test Failure
How To Take Multiple Screenshots in Selenium?
TakesScreenshot screenshot = (TakesScreenshot) driver;
File srcFile = screenshot.getScreenshotAs (OutputType.FILE);
FileUtils.copyFile (srcFile, new File (`` path/to/save/imageName.png ''));
How to get the driver target in TestListeners using TestNG?
Passing WebDriver via ThreadLocal or Base Class
private stable ThreadLocal & lt; WebDriver & gt; driver = new ThreadLocal & lt; & gt; (); public static WebDriver getDriver () {homecoming driver.get ();}public class BaseTest {protect WebDriver driver; @ BeforeMethod public void setUp () {driver = new ChromeDriver ();}}Using ITestResult to Capture Test Name for Screenshot
public void onTestFailure (ITestResult termination) {WebDriver driver = getDriver (); File screenshot = ((TakesScreenshot) driver) .getScreenshotAs (OutputType.FILE); FileUtils.copyFile (screenshot, new File (`` screenshots/ '' + result.getName () + `` .png ''));}Example of Selenium Screenshot
TakesScreenshot scrShot = ((TakesScreenshot) webdriver);
File SrcFile=scrShot.getScreenshotAs (OutputType.FILE);
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);}}Scale Selenium Screenshots across Real Browsers with BrowserStack Automate
Conclusion
FAQs
Related Guides
Automate This With SUSA
Test Your App Autonomously