544

Is it possible to take a screenshot using Selenium WebDriver?

(Note: Not Selenium Remote Control)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Hollingworth
  • 14,040
  • 12
  • 39
  • 57
  • There is probably only one way to do this with the WebDriver Wire Protocol, but no one uses this protocol directly. Instead, people use different language bindings/libraries which wrap the low-level protocol. There are loads of language bindings, so you need to say which one you want to use. Otherwise, there are just too many answers. – oberlies May 15 '14 at 16:42
  • Which programming language are you using? – Ripon Al Wasim Apr 12 '16 at 11:07
  • Do you want to take a screenshot of whole page or a specific element? – Ripon Al Wasim Apr 12 '16 at 11:07
  • Yes, it is possible to take screenshot either entire page or for a specific element with Selenium WebDriver – Ripon Al Wasim Nov 16 '16 at 10:43

51 Answers51

552

Java

Yes, it is possible. The following example is in Java:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Sergii Pozharov
  • 17,366
  • 4
  • 29
  • 30
  • 33
    Copying the file, rather than renaming it, is a good idea if there is any chance that the source and destination might not be on the same filesystem. You can't rename across filesystem boundaries (on unix, at least). Note that it's common for `/tmp` to be on its own filesystem, and FirefoxDriver writes screenshots to `/tmp`. – Tom Anderson Dec 15 '11 at 17:43
  • 9
    Is there a way to do it only for failed cases? – some_other_guy Aug 23 '12 at 05:54
  • You can do a sparse copy and get better performance when they are on the same filesystem. – Janus Troelsen Aug 28 '12 at 11:06
  • Is this a cross-browser solution or works in only Firefox..? What are the packages to be imported in our java application? Can you provide a complete example,if possible since I have the same requirement but I could not understand the above coding part.... – Rama Rao M Oct 04 '12 at 13:13
  • That should work on any browser that have driver that implements TakesScreenshot - it works on IE for sure – Sergii Pozharov Feb 14 '13 at 11:12
  • This question is a bit old, but for anyone else coming across this and having issues: In order to get it to work, I had to add a `File` cast around `TakesScreenshot`. (i.e. `File srcFile = (File) (((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));`) It then worked like a charm. – KPM Jun 16 '13 at 01:59
  • I'm having trouble getting it to work for Android. Has anybody had any luck with that? – David West Jun 26 '13 at 17:44
  • 6
    It's worth noting that `HtmlUnitDriver` doesn't implement `TakesScreenshot` (see http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html for a list of supported drivers). But you can save as HTML. – Wernight Jul 12 '13 at 10:28
  • Can any tell me that File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE) getScreenShotAs is the method in the TakesScreenshot Interface......(TakesScreenshot)driver, What is this one??? can you please explain little bit? – ChanGan Feb 19 '14 at 10:19
  • If anyone tried this and got a casting exception, using the AugmentedDriver is the way to go. I found this blog post that helped get past the exception: http://rkchunduri.blogspot.com/2011/11/remotewebdriver-cannot-be-cast-to.html – CatsAndCode Feb 20 '14 at 21:22
  • 10
    What package is required to import for using FileUtils class? – Ripon Al Wasim Apr 10 '14 at 06:20
  • 11
    @RiponAlWasim probably `org.apache.commons.io.FileUtils` – Ben Jul 31 '14 at 15:25
  • @Steve , Old habit, just accepted whatever Eclipse suggested (com.sun.jna.platform.FileUtils) and pulled hair till found Steve's comment buried here. Thanks! – Payam Feb 12 '15 at 20:19
  • Why do you copy the file. I guess ` final byte[] screenshot = ((TakesScreenshot) wrappedDriver) .getScreenshotAs(OutputType.BYTES); FileUtils.writeByteArrayToFile(new File(screenshotFileName + ".png"), screenshot); ' should be faster. – niels Aug 05 '15 at 05:19
  • This only works for Local runs. You need the Augmenter class otherwise for screen shots – Jason Smiley Dec 28 '15 at 20:52
  • 1
    Just in case you want to take a screenshot in a JUnit test. The following article describes how to use a TestWatcher for taking screenshots: http://www.thinkcode.se/blog/2012/07/08/performing-an-action-when-a-test-fails – Leukipp Jul 28 '16 at 00:04
  • @Some_other_guy, Yes, you can add this code to your `@After` method. Here's a link that goes into more detail: http://stackoverflow.com/a/22776020/7015351 Also, depending on your implementation, you may want to create logic so that each screenshot has a unique filename. Otherwise, you may continually overwrite the previous screenshot after every test failure. – Zachary David Saunders Apr 02 '17 at 04:44
  • @ali-asgari According to Selenium Java Doc it uses png internally, so you will need to get as png bytes (use OutputType.BYTES instead) and then convert to jpg - see https://stackoverflow.com/questions/2290336/converting-png-into-jpeg – Sergii Pozharov Sep 07 '20 at 08:13
321

Python

Each WebDriver has a .save_screenshot(filename) method. So for Firefox, it can be used like this:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')

Confusingly, a .get_screenshot_as_file(filename) method also exists that does the same thing.

There are also methods for: .get_screenshot_as_base64() (for embedding in HTML) and .get_screenshot_as_png()(for retrieving binary data).

And note that WebElements have a .screenshot() method that works similarly, but only captures the selected element.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
  • For other browsers, exchange the webdriver instance. If you just want screenshots of your website including state, have a look at [Usersnap](http://usersnap.com). – Gregor Aug 22 '13 at 13:04
  • @DavidRöthlisberger thats all great, but your comment has nothing to do with my answer – Corey Goldberg Feb 26 '17 at 21:12
  • To make a scrennshot of a full page, not only the visible area, use my python code from my answer here to stich: http://stackoverflow.com/questions/37906704/taking-a-whole-page-screenshot-with-selenium-marionette-in-python – Martin Krung Mar 02 '17 at 12:41
  • @FabianThommen scrolling/stitching has its own set of issues and is often not a viable solution. (also, your comment has nothing to do with my answer) – Corey Goldberg Nov 27 '17 at 15:45
  • 2
    @CoreyGoldberg True, nothing to do with your answer. But my old script used a older FF and it did take the whole page, not only the viewport. After they changed it to standard now only viewport. So I wanted to help somebody having the same problem. And yes, fixed element are a real pain in scroll/stich! – Martin Krung Nov 28 '17 at 10:57
  • Is there a way to change/set output file extension. – Ahsan Roy Jul 28 '18 at 10:04
  • @AhsanRoy you can use whatever file extension you like when you name the output file, but the format is PNG. – Corey Goldberg Jul 28 '18 at 21:21
  • 3
    One more thing that helped me immensely, if you need to change the image dimension, simply set the window size before you take the snapshot using `driver.set_window_size(1366, 728)`. – srdg Jun 05 '19 at 18:41
  • what is the best image dimension that could be taken to work for different setups as well. meaning smallest screen size. thanks. – someuser2491 Sep 27 '19 at 09:03
119

C#

public void TakeScreenshot()
{
    try
    {            
        Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
        ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
jessica
  • 1,507
  • 3
  • 15
  • 18
  • 10
    Works perfectly. Caveat: takes a screen shot not a page shot. – ljgww Apr 23 '15 at 07:15
  • do you mean it gets desktop and everything? Or you mean that it just gets the viewport? – vtortola Mar 01 '17 at 15:11
  • It will only get what is in the scope of the driver, this is to allow multiple parallel tests taking place. Note that it will not zoom out if your driver's main window focus has a scrollbar or if it exceeds a single page. – Ben Mar 28 '17 at 19:50
  • 3
    update to SaveAsFile(string path, ScreenshotImageFormat format) ScreenshotImageFormat.Jpeg – Kieran Aug 01 '17 at 02:06
  • 1
    This worked for me! I was using CopyFromScreen from the Graphics namespace. The advantage of the above solution is that it works when the code is called in a headless way from TFS. My old CopyFromScreen method only worked when running selenium tests from Visual Studio but never worked for my TFS run tests. – Ewan Oct 11 '19 at 16:15
  • "Error CS1069: The type name 'ImageFormat' could not be found in the namespace 'System.Drawing.Imaging'. This type has been forwarded to assembly 'System.Drawing.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' Consider adding a reference to that assembly. (CS1069) (xUnit_MSSO)" – BSUK Mar 11 '22 at 21:42
86

JavaScript (Selenium-Webdriver)

driver.takeScreenshot().then(function(data){
   var base64Data = data.replace(/^data:image\/png;base64,/,"")
   fs.writeFile("out.png", base64Data, 'base64', function(err) {
        if(err) console.log(err);
   });
});
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Moiz Raja
  • 5,612
  • 6
  • 40
  • 52
  • 3
    Similar to how Browserstack describes it: http://www.browserstack.com/automate/node#enhancements-screenshots – Mike Causer Dec 24 '13 at 07:40
  • in data.replace what exactly are you doing in the parenthesis? – John Demetriou Apr 06 '15 at 07:26
  • @JohnDemetriou, data is the name of the object or variable that will be created when you call it. U can call it `var1` if you wish. U should look at `takeScreenshot()` function to know what exactly it is. Maybe a binary image rendered from javascript using canvas. It can be the dom, before it's rendered. Look into. – m3nda Jun 10 '16 at 01:21
71

Ruby

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")

More file types and options are available and you can see them in file takes_screenshot.rb.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sirclesam
  • 2,109
  • 17
  • 13
  • Worked fine for me using Selenium Grid 2. Script and hub running on OS X Snow Leopard; node running on RedHat EL 4 with Firefox 3.6.18 under Xvfb. – MarkD Dec 06 '11 at 22:33
  • 2
    Is there any way to take the full page screenshot, not just the visible area? – Arihant Godha Aug 28 '14 at 06:38
  • 2
    Full page is taken by default. At least using `headless` and `Firefox` – Ashley Feb 17 '15 at 09:59
  • Why parentheses for `driver.save_screenshot`, but not for `driver.get`? – Peter Mortensen Nov 05 '20 at 21:59
  • @PeterMortensen - Not sure and its been long enough since I used Ruby that I don't remember if there's any functional difference between the two...my gut says their the same...but I'd suggest full parens for safety reasons. – sirclesam Dec 16 '20 at 00:53
37

Java

I got this issue resolved. You can augment the RemoteWebDriver to give it all of the interfaces its proxied driver implements:

WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user708910
  • 551
  • 5
  • 6
  • If you do that, then don't you need to copy screenshots to a filename with threadId so that you can tell which threads/instances of your driver threw the screenshot? Otherwise, multiple instances of a browser on one grid node would overwrite each others screenshots? – djangofan Sep 06 '13 at 17:42
  • 1
    I would like to point it out that only this solution worked for me using headless ChromeDriver – rado Oct 10 '18 at 00:13
34

PHP (PHPUnit)

It uses PHPUnit_Selenium extension version 1.2.7:

class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
    ...
    public function screenshot($filepath) {
        $filedata = $this->currentScreenshot();
        file_put_contents($filepath, $filedata);
    }

    public function testSomething() {
        $this->screenshot('/path/to/screenshot.png');
    }
    ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ryan Mitchell
  • 1,410
  • 1
  • 14
  • 23
  • daaaamn! I wanna know more about this, Selenium is new to me and I'm looking for a cli solution to creating screenshots across a number of browsers and OSes to do visual tests – pythonian29033 Jul 07 '16 at 12:19
31

C#

public Bitmap TakeScreenshot(By by) {
    // 1. Make screenshot of all screen
    var screenshotDriver = _selenium as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
wsbaser
  • 1,178
  • 10
  • 7
19

Java

public String captureScreen() {
    String path;
    try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
        path = "./target/screenshots/" + source.getName();
        FileUtils.copyFile(source, new File(path)); 
    }
    catch(IOException e) {
        path = "Failed to capture screenshot: " + e.getMessage();
    }
    return path;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
SilverColt
  • 409
  • 3
  • 4
13

Jython

import org.openqa.selenium.OutputType as OutputType
import org.apache.commons.io.FileUtils as FileUtils
import java.io.File as File
import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver

self.driver = FirefoxDriver()
tempfile = self.driver.getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(tempfile, File("C:\\screenshot.png"))
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Fresh Mind
  • 131
  • 1
  • 2
12

Java (Robot Framework)

I used this method for taking a screenshot.

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000)
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

You may use this method wherever required.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ank
  • 121
  • 1
  • 2
10

Java

Seems to be missing here - taking screenshot of a specific element in Java:

public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Erki M.
  • 5,022
  • 1
  • 48
  • 74
  • I don't think this approach actual can work, as the the screenshot and the actual browser have different resolutions. So when using the coordinate location obtained by selenium on your image you're pretty sure to run into a java.awt.image.RasterFormatException: (y + height) is outside of Raster – Ichwardort Nov 26 '15 at 16:23
  • Did you try the code? It worked when I last tried it. – Erki M. Nov 27 '15 at 08:22
  • 1
    It works perfectly fine as long as you try capturing an element which is visible without scrolling. When you need to scroll to an element to capture it, then the y offset is calculated from the top of the page, which then exceeds the boundaries of the full-screen image. So the easiest solution is to either increase the screen size `code` this.driver.manage().window().setSize(new Dimension(1680, 1050)); or to remove any non required elements via css. The proper solution would be to calculate the y-offset from scrolling. – Ichwardort Nov 27 '15 at 08:57
  • 1
    In **`Firefox`** works fine as it crops the element screen from full Image based on Dimensions. In **`Chrome`** if the element is available in view portion with out scrolling the from that view portion image it captures element fine. If we want to take screenshot after scrolling `document.documentElement.clientHeight` two times of client Height the use `(location.y)-2*clientHeight` to get exact element screenshot. Thanks for this post as it helps me... – Yash Aug 19 '16 at 05:58
  • It doesn't work for me. Instead of taking the screenshot of a particular element (which it's supposed to do), it takes the screenshot of the entire visible screen. P.S. I'm using ChromeDriver 89. – Tech Expert Wizard Apr 12 '21 at 02:20
8

C#

using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;

namespace example.com
{
    class Program
    {
        public static PhantomJSDriver driver;

        public static void Main(string[] args)
        {
            driver = new PhantomJSDriver();
            driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
            driver.Navigate().GoToUrl("http://www.example.com/");
            driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
            driver.Quit();
        }
    }
}

It requires NuGet packages:

  1. PhantomJS 2.0.0
  2. Selenium.Support 2.48.2
  3. Selenium.WebDriver 2.48.2

It was Tested with .NET Framework v4.5.2.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
userlond
  • 3,632
  • 2
  • 36
  • 53
5

PowerShell

Set-Location PATH:\to\selenium

Add-Type -Path "Selenium.WebDriverBackedSelenium.dll"
Add-Type -Path "ThoughtWorks.Selenium.Core.dll"
Add-Type -Path "WebDriver.dll"
Add-Type -Path "WebDriver.Support.dll"

$driver = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver

$driver.Navigate().GoToUrl("https://www.google.co.uk/")

# Take a screenshot and save it to filename
$filename = Join-Path (Get-Location).Path "01_GoogleLandingPage.png"
$screenshot = $driver.GetScreenshot()
$screenshot.SaveAsFile($filename, [System.Drawing.Imaging.ImageFormat]::Png)

Other drivers...

$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
$driver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver
$driver = New-Object OpenQA.Selenium.Opera.OperaDriver
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
TechSpud
  • 3,418
  • 1
  • 27
  • 35
  • Probably better to use `[OpenQA.Selenium.ScreenshotImageFormat]::Png` than `System.Drawing` namespace. – Adarsha May 22 '17 at 19:00
5

There are multiple methods through Selenium's Java and Python client to take a screenshot using Selenium WebDriver.


Java Methods

The following are the different Java methods to take a screenshot:

  • Using getScreenshotAs() from the TakesScreenshot interface:

  • Code block:

         package screenShot;
    
         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.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         public class Firefox_takesScreenshot {
    
             public static void main(String[] args) throws IOException {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://login.bws.birst.com/login.html/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst"));
                 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                 FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    Mads_Cruz_screenshot

  • If the webpage is jQuery enabled, you can use from the pazone/ashot library:

  • Code block:

         package screenShot;
    
         import java.io.File;
         import javax.imageio.ImageIO;
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import org.openqa.selenium.support.ui.ExpectedConditions;
         import org.openqa.selenium.support.ui.WebDriverWait;
    
         import ru.yandex.qatools.ashot.AShot;
         import ru.yandex.qatools.ashot.Screenshot;
         import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
    
         public class ashot_CompletePage_Firefox {
    
             public static void main(String[] args) throws Exception {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://jquery.com/");
                 new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery"));
                 Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
                 ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png"));
                 driver.quit();
             }
         }
    
  • Screenshot:

    firefoxScreenshot.png

  • Using from assertthat/selenium-shutterbug library:

  • Code block:

         package screenShot;
    
         import org.openqa.selenium.WebDriver;
         import org.openqa.selenium.firefox.FirefoxDriver;
         import com.assertthat.selenium_shutterbug.core.Shutterbug;
         import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy;
    
         public class selenium_shutterbug_fullpage_firefox {
    
             public static void main(String[] args) {
    
                 System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
                 WebDriver driver =  new FirefoxDriver();
                 driver.get("https://www.google.co.in");
                 Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/");
                 driver.quit();
             }
         }
    
  • Screenshot:

    2019_03_12_16_30_35_787.png


Python Methods

The following are the different Python methods to take a screenshot:

  • Using save_screenshot() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.save_screenshot('./Screenshots/save_screenshot_method.png')
         driver.quit()
    
  • Screenshot:

    save_screenshot_method.png

  • Using the get_screenshot_as_file() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png')
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_file_method.png

  • Using get_screenshot_as_png() method:

  • Code block:

         from selenium import webdriver
    
         driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
         driver.get("http://google.com")
         screenPnG = driver.get_screenshot_as_png()
    
         # Crop it back to the window size (it may be taller)
         box = (0, 0, 1366, 728)
         im = Image.open(BytesIO(screenPnG))
         region = im.crop(box)
         region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95)
         driver.quit()
    
  • Screenshot:

    get_screenshot_as_png_method.png

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
4

Java

I could not get the accepted answer to work, but as per the current WebDriver documentation, the following worked fine for me with Java 7 on OS X v10.9 (Mavericks):

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

   public void myTest() throws Exception {
       WebDriver driver = new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"),
               DesiredCapabilities.firefox());

       driver.get("http://www.google.com");

       // RemoteWebDriver does not implement the TakesScreenshot class
       // if the driver does have the Capabilities to take a screenshot
       // then Augmenter will add the TakesScreenshot methods to the instance
       WebDriver augmentedDriver = new Augmenter().augment(driver);
       File screenshot = ((TakesScreenshot)augmentedDriver).
               getScreenshotAs(OutputType.FILE);
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steve HHH
  • 12,947
  • 6
  • 68
  • 71
4

C#

public static void TakeScreenshot(IWebDriver driver, String filename)
{
    // Take a screenshot and save it to filename
    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    screenshot.SaveAsFile(filename, ImageFormat.Png);
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
dmeehan
  • 2,317
  • 2
  • 26
  • 31
3

Ruby (Cucumber)

After do |scenario| 
    if(scenario.failed?)
        puts "after step is executed"
    end
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'

    page.driver.browser.save_screenshot file_path
end

Given /^snapshot$/ do
    time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')

    file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
    page.driver.browser.save_screenshot file_path
end
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
vijay chouhan
  • 1,012
  • 8
  • 25
3

Ruby

time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
#driver.save_screenshot(file_path)
page.driver.browser.save_screenshot file_path
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
vijay chouhan
  • 1,012
  • 8
  • 25
3

PHP

public function takescreenshot($event)
  {
    $errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";

    if(!file_exists($errorFolder)){
      mkdir($errorFolder);
    }

    if (4 === $event->getResult()) {
      $driver = $this->getSession()->getDriver();
      $screenshot = $driver->getWebDriverSession()->screenshot();
      file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' .  time() . '.png', base64_decode($screenshot));
    }
  }
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Arpan Buch
  • 1,380
  • 5
  • 19
  • 41
  • in the current version of facebook/webdriver the method is takeScreenshot() and it is not necessary to base64_encode() the output before saving the file. – billrichards Feb 26 '16 at 03:09
  • 2
    Could you please add code to your example that shows how to call this `takescreenshot` function? Specifically where does the `$event` variable come from? I am a complete Selenium noob so an answer to this question that doesn't assume prior Selenium knowledge would be very much appreciated! – Kenny83 Sep 30 '18 at 13:20
2

Java

Using RemoteWebDriver, after augmenting the Node with screenshot capability, I would store the screenshot like so:

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000);
        long id = Thread.currentThread().getId();
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(
            Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/"
            + id + "/screenshot.jpg"));
    }
    catch( Exception e ) {
        e.printStackTrace();
    }
}

You may use this method wherever required. Then, I assume you can customize the style sheet of maven-surefire-report-plugin at surefire-reports/html/custom.css so that your reports include the link to the correct screenshot for each test?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
djangofan
  • 28,471
  • 61
  • 196
  • 289
2

Java

String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername";

// Take a snapshort
File snapshort_file = ((TakesScreenshot) mWebDriver)
        .getScreenshotAs(OutputType.FILE);
// Copy the file into folder

FileUtils.copyFile(snapshort_file, new File(yourfilepath));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yerram Naveen
  • 286
  • 5
  • 16
2

Java

public void captureScreenShot(String obj) throws IOException {
    File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshotFile, new File("Screenshots\\" + obj + "" + GetTimeStampValue() + ".png"));
}

public String GetTimeStampValue()throws IOException{
    Calendar cal = Calendar.getInstance();
    Date time = cal.getTime();
    String timestamp = time.toString();
    System.out.println(timestamp);
    String systime = timestamp.replace(":", "-");
    System.out.println(systime);
    return systime;
}

Using these two methods you can take a screen shot with the date and time as well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raghuveer
  • 115
  • 2
  • 10
2

Selenese

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bernát
  • 1,362
  • 14
  • 19
2

Python

def test_url(self):
    self.driver.get("https://www.google.com/")
    self.driver.save_screenshot("test.jpg")

It will save a screenshot in the same directory the where script is saved.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hemant
  • 99
  • 2
2

You can give a try to AShot API. It is on GitHub.

Examples of tests.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Khaja Mohammed
  • 769
  • 6
  • 16
2

C#

You can use the following code snippet/function to take screenshot with Selenium:

    public void TakeScreenshot(IWebDriver driver, string path = @"output")
    {
        var cantakescreenshot = (driver as ITakesScreenshot) != null;
        if (!cantakescreenshot)
            return;
        var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
        filename = path + @"\" + filename + ".png";
        var ss = ((ITakesScreenshot)driver).GetScreenshot();
        var screenshot = ss.AsBase64EncodedString;
        byte[] screenshotAsByteArray = ss.AsByteArray;
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        ss.SaveAsFile(filename, ImageFormat.Png);
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohsin Awan
  • 1,176
  • 2
  • 12
  • 29
  • "using System.Drawing.Imaging;" assembly. – ArNumb Jan 22 '17 at 21:16
  • I had to use this line in the SaveAsFile call: ss.SaveAsFile(filename, ScreenshotImageFormat.Png); I also prefer to use Path.Combine(folder, filename) over the path + @"\" because it reads better, and I think it *may* be more forgiving of folder/filename formatting.variations. Personal preference only. So that line becomes: filename = Path.Combine(path, filename + ".png"); – Developer63 Jun 27 '19 at 09:08
2

Java

A method to capture a screenshot for the failures in Selenium with TestName and Timestamp appended.

public class Screenshot{
    final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
    public static String imgname = null;

    /*
     * Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
     */
    public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
      try {
      String imgpath = System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
      File f = new File(imgpath);
      if(!f.exists())   {
          f.mkdir();
        }
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
        String timestamp = sd.format(d);
        imgname = imgpath + "\\" + timestamp + ".png";

        // Snapshot code
        TakesScreenshot snpobj = ((TakesScreenshot)wb);
        File srcfile = snpobj.getScreenshotAs(OutputType.FILE);
        File destFile = new File(imgname);
        FileUtils.copyFile(srcfile, destFile);

      }
      catch(Exception e) {
          e.getMessage();
      }
   }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anuj Teotia
  • 1,303
  • 1
  • 15
  • 21
  • If you found this (or any) answer helpful, please upvote it. If this answered your question, please mark it as the accepted answer. Thanks! – Anuj Teotia Apr 01 '17 at 19:50
2

Updated 2022

To take a screenshot in Selenium, we use an interface called TakesScreenshot, which enables the Selenium WebDriver to capture a screenshot and store it in different ways. It has a got a method getScreenshotAs() which captures the screenshot and stores it in the specified location.

//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

In the above code, its convert the WebDriver object (driver) to TakeScreenshot. And call getScreenshotAs() method to create an image file by providing the parameter *OutputType.FILE.

We can use the File object to copy the image at our desired location, as shown below, using the FileUtils Class.

FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));

Capture the full page

Selenium WebDriver doesn't provide the inherent capability to capture screenshots of the whole page. To capture the full-page screenshot, we have to use a third-party library named Ashot. It provides the ability to take a screenshot of a particular WebElement as well as a full-page screenshot.

Capture the screen size image

Screenshot screenshot = new Ashot().takeScreenshot(driver);

Capture the full page screenshot

Screenshot s=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("<< file path>>"));

In the above code, 1000 is scrolled out time in milliseconds. In other words, it means that the program will scroll for each 1000 msec to take a screenshot.

Capture a elememnt

There are two ways to capture the screenshot of a web element in Selenium.

  • Take the fullscreen image and then crop the image as per the dimensions of the web element.
  • Using the getScreenshotAs() method on the web element. ( This is available only in selenium version 4.X)
pr96
  • 994
  • 5
  • 17
1

Python

You can capture the image from windows using the Python web driver. Use the code below which page need to capture the screenshot.

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kv.senthilkumar
  • 936
  • 2
  • 16
  • 29
1

C# (Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Benny Meade
  • 602
  • 10
  • 25
1

Java

I thought I would give my full solution since there are two different ways of getting a screenshot. One is from the local browser, and one is from the remote browser. I even embed the image into the HTML report:

@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {

    if (scenario.isFailed()){

        scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");

        try{
            driver.manage().window().maximize();  // Maximize window to get full screen for chrome
        }
        catch (org.openqa.selenium.WebDriverException e){
            System.out.println(e.getMessage());
        }

        try {
            if(isAlertPresent()){
                Alert alert = getAlertIfPresent();
                alert.accept();
            }
            byte[] screenshot;
            if(false /*Remote Driver flow*/) { // Get a screenshot from the remote driver
                Augmenter augmenter = new Augmenter();
                TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
                screenshot = ts.getScreenshotAs(OutputType.BYTES);
            } 
            else { // Get a screenshot from the local driver
                // Local webdriver user flow
                screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            }
            scenario.embed(screenshot, "image/png"); // Embed the image in reports
        } 
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } 
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }

    //seleniumCleanup();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason Smiley
  • 289
  • 4
  • 12
1

Selenide / Java

Here is how the Selenide project does it, making it easier than just about any other way of doing it:

import static com.codeborne.selenide.Selenide.screenshot;    
screenshot("my_file_name");

For JUnit:

@Rule
public ScreenShooter makeScreenshotOnFailure = 
     ScreenShooter.failedTests().succeededTests();

For TestNG:

import com.codeborne.selenide.testng.ScreenShooter;
@Listeners({ ScreenShooter.class})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
djangofan
  • 28,471
  • 61
  • 196
  • 289
1

Robot Framework

Here is a solution using Robot Framework with the Selenium2Library:

*** Settings ***
Library                        Selenium2Library

*** Test Cases ***
Example
    Open Browser               http://localhost:8080/index.html     firefox
    Capture Page Screenshot

This will save a screenshot in the working space. It is also possible to supply a filename to the keyword Capture Page Screenshot to change that behavior.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jotrocken
  • 2,263
  • 3
  • 27
  • 38
1

C# code

IWebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((ITakesScreenshot)driver).GetScreenshotAs(OutputType.FILE);

// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rakesh Raut
  • 183
  • 3
  • 12
1

Yes, it is possible to take a snapshot of a web page using Selenium WebDriver.

The getScreenshotAs() method provided by the WebDriver API does the work for us.

Syntax: getScreenshotAs(OutputType<X> target)

Return type: X

Parameters: target – Check the options provided by OutputType

Applicability: Not specific to any DOM element

Example:

    TakesScreenshot screenshot = (TakesScreenshot) driver;
    File file = screenshot.getScreenshotAs(OutputType.FILE);

Refer to the below working code snippet for more details.

    public class TakeScreenShotDemo {

        public static void main(String[] args) {
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.get(“http: //www.google.com”);

            TakesScreenshot screenshot = (TakesScreenshot) driver;

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

            // Creating a destination file
            File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
            try {
                FileUtils.copyFile(file, destination);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

Visit Snapshot using WebDriver for getting more details.

renemadsen
  • 161
  • 1
  • 9
1

You can use the ashot library to take screenshots in Selenium WebDriver. Here's an example:

First, you need to add the ashot dependency to your project:

<dependency>
    <groupId>ru.yandex.qatools.ashot</groupId>
    <artifactId>ashot</artifactId>
</dependency>

Then, you can take a screenshot using the following code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

public class ScreenshotExample {
    public static void main(String[] args) throws IOException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        Screenshot screenshot = new AShot().takeScreenshot(driver);
        ImageIO.write(screenshot.getImage(), "PNG", new File("screenshot.png"));
        driver.quit();
    }
}

This will take a screenshot of the current page and save it to a file named "screenshot.png".

Lakshitha Samod
  • 383
  • 3
  • 10
1

You can create a webdriverbacked selenium object using the Webdriverclass object, and then you can take a screenshot.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RosAng
  • 1,010
  • 2
  • 18
  • 42
0

I use the following code in C# to take the full page or only a browser screenshot

    public void screenShot(string tcName)
    {
        try
        {
            string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
            string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
            ITakesScreenshot screen = driverScript.driver as ITakesScreenshot;
            Screenshot screenshot = screen.GetScreenshot();
            screenshot.SaveAsFile(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
            if (driverScript.last == 1)
                this.writeResult("Sheet1", "Fail see Exception", "Status", driverScript.resultRowID);
        }
        catch (Exception ex)
        {
            driverScript.writeLog.writeLogToFile(ex.ToString(), "inside screenShot");
        }
    }

    public void fullPageScreenShot(string tcName)
    {
        try
        {
            string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
            string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
            Rectangle bounds = Screen.GetBounds(Point.Empty);
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }
                bitmap.Save(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
            }
            if (driverScript.last == 1)
                this.writeResult("Sheet1", "Pass", "Status", driverScript.resultRowID);
        }
        catch (Exception ex)
        {
            driverScript.writeLog.writeLogToFile(ex.ToString(), "inside fullPageScreenShot");
        }
    }
renemadsen
  • 161
  • 1
  • 9
Aman Sharma
  • 311
  • 1
  • 8
  • 22
0
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
Alistra
  • 5,177
  • 2
  • 30
  • 42
0
public static void getSnapShot(WebDriver driver, String event) {

    try {
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        BufferedImage originalImage = ImageIO.read(scrFile);
        //int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
        ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
        Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
        jpeg.setAlignment(Image.MIDDLE);
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell1 = new PdfPCell(new Paragraph("\n"+event+"\n"));
        PdfPCell cell2 = new PdfPCell(jpeg, false);
        table.addCell(cell1);
        table.addCell(cell2);
        document.add(table);
        document.add(new Phrase("\n\n"));
        //document.add(new Phrase("\n\n" + event + "\n\n"));
        //document.add(jpeg);
        fileWriter.write("<pre>        " + event + "</pre><br>");
        fileWriter.write("<pre>        " + Calendar.getInstance().getTime() + "</pre><br><br>");
        fileWriter.write("<img src=\".\\img\\" + index + ".jpg\" height=\"460\" width=\"300\"  align=\"middle\"><br><hr><br>");
        ++index;
    }
    catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Python

webdriver.get_screenshot_as_file(filepath)

The above method will take a screenshot and also store it as a file in the location provided as a parameter.

Sajid Manzoor
  • 487
  • 1
  • 5
  • 9
0

Yes, it is possible to take screenshots via Selenium WebDriver. I currently use Chrome Driver for snapping images of websites. Please refer the following method captureScreenshot().

You can also add restriction towards web driver, such as

  • use headless version of web browser
  • disable notification when page loads
  • start full screen, etc.

If a website is equipped with Alert Box, your web driver will not be able to capture screenshot since exception will be thrown. In that scenario you need to close the alert box and then get the screenshot. Following code fragment does the closing of alert box.

    public void captureScreenshot() throws InterruptedException, IOException {

        System.out.println("Creating Chrome Driver");

        // Set Chrome Driver
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        // Add arguments to Chrome Options
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("start-maximized");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--start-fullscreen");
        chromeOptions.addArguments("--disable-extensions");
        chromeOptions.addArguments("--disable-popup-blocking");
        chromeOptions.addArguments("--disable-notifications");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--dns-prefetch-disable");
        chromeOptions.addArguments("enable-automation");
        chromeOptions.addArguments("disable-features=NetworkService");

        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.google.com");
        System.out.println("Wait a bit for the page to render");
        TimeUnit.SECONDS.sleep(5);
        System.out.println("Taking Screenshot");
        File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String imageDetails = "D:\\Images";
        File screenShot = new File(imageDetails).getAbsoluteFile();
        FileUtils.copyFile(outputFile, screenShot);
        System.out.println("Screenshot saved: {}" + imageDetails);
    }
}

In order to accept Alert Box and Get Screenshot:

String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "D://Images"
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
0

Java

For newer version of Java, the FileUtils function doesn't work. Here the following function worked perfectly for screenshot copying.

import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.io.FileHandler;

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File destfile = new File(destination folder /filename.extension);
FileHandler.copy(scrfile, destfile);
RiveN
  • 2,595
  • 11
  • 13
  • 26
0
/**
 * Take a screenshot and move to the given folder location.
 *
 * @param driver
 * @param folderLocation
 * @return screenShotFilePath
 */
public static String captureScreenshot(WebDriver driver, String folderLocation) {

    // Variable to store screenshot's file path.
    String screenShotFilePath = null;

    // Generate unique id for screen shot name.
    String uniqueId = UUID.randomUUID().toString().substring(31);

    if (driver != null) {

        // Generate screenshot as a file
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // New screenshot file path with having file name
        screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";

        // Move file to the destination location.
        FileUtils.moveFile(scrFile, new File(screenShotFilePath));
    }

    return screenShotFilePath;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Using C# and MSTestframework, Here I have created a static method. Taken a path where I can store the images as jpeg format. to make more clear I am naming those screen shots with current Executing Testcases and date and time of the failure.

          /// <summary>
            /// This method is used to screen shot where test method failed 
            /// </summary>
            /// <param name="testCase">TestCaseName</param>
            public static void Capture(string testCase)
            {
                try
                {
                    StringBuilder path = new StringBuilder("C:/Logs/Screenshot/");
                    Constant.screenshot = ((ITakesScreenshot)Constant.browser).GetScreenshot();
                    string fileName = path.Append(string.Format(testCase + "-at-{0:yyyy-MM dd_hh-mm-ss}.jpeg", DateTime.Now)).ToString();
                    Constant.screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Jpeg);
                }
                catch (Exception e)
                {
                    File.AppendAllText("C:/Logs/FailedTestCasesLogs.txt", "\nCOULD NOT CAPTURE THE SCREENSHOT!\n");
                    Log(e);
                }
    
            }
AmitKS
  • 132
  • 4
0

You can take screenshot of webpage visible portion in browser as:

First import:

import java.io.File;
import com.google.common.io.Files;

Then

File src=((TakesScreenshot)driver).getScreenShotAs(OutputType.FILE);
Files.copy(src,new File("new path/pic.jpeg"));

Plus after Selenium4 you can also take screenshot of webelement as:

WebElement element=driver.findElement(By.xpath("xpath 
 here"));
File src=element.getScreenShotAs(OutputType.FILE);
File.copy(src,new File("new path/pic.jpeg"));
a Learner
  • 4,944
  • 10
  • 53
  • 89
0

JAVA

Hi, you can take screenshot in selenium and here is the code given below with the help of which you can create screenshot in any selenium project and we can also generate screenshots for the failed scenario's in aws too.

    public boolean takeScreenshot(final String name) {
    String screenshotDirectory = System.getenv("WORKING_DIRECTORY");
    File screenshot = 
    ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    return screenshot.renameTo(new File(screenshotDirectory, 
    String.format("%s.png", name)));
    }
Rutu Shah
  • 11
  • 3
0

Excel VBA

Option Explicit

Private Sub Login()
    Dim driver As ChromeDriver
    Set driver = New ChromeDriver
    Dim sURL As String
    sURL = "https://www.bing.com/"
    Dim sFilename As String
    sFilename = "C:\Users\username\Downloads\screenshot-" & sURL & "-" & Format(Now(), "yyyymmddHHMMSS") & ".png"
    sFilename = Replace(sFilename, "://", "")
    sFilename = Replace(sFilename, "/", "")
    Call driver.Start("edge", sURL)
    driver.get (sURL)
    driver.Window.Maximize
    sbDelay (100000)
    driver.TakeScreenshot.SaveAs (sFilename)
    sbDelay (100000)
    driver.Quit
End Sub

Sub sbDelay(delay As Long): Dim i As Long: For i = 1 To delay:  DoEvents: Next i: End Sub 'old skool delay

I used the VBA type library that Microsoft support

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

I used MS Edge - the Selenium version must match the version of Edge that you have installed.

Edge Version 110.0.1587.57

You will need to browse to the type library for your machine either 32 or 64 bit.

Tools > References > Selenium Type Library (Selenium64.tlb)

user10186832
  • 423
  • 1
  • 9
  • 17
0

C# Selenium 4.9

driver.TakeScreenshot().SaveAsFile(path + filename + ".jpg");

Nomad77
  • 105
  • 3
-2
import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}
Jagdeep
  • 139
  • 3
  • 12
  • Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference. – kleopatra Jan 29 '16 at 07:10
  • An explanation would be in order. – Peter Mortensen Nov 19 '20 at 21:25