538

Is it possible to take a screenshot using Selenium WebDriver?

(Note: Not Selenium Remote Control)

4
  • 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, 2014 at 16:42
  • Which programming language are you using? Apr 12, 2016 at 11:07
  • Do you want to take a screenshot of whole page or a specific element? Apr 12, 2016 at 11:07
  • Yes, it is possible to take screenshot either entire page or for a specific element with Selenium WebDriver Nov 16, 2016 at 10:43

51 Answers 51

547

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"));
18
  • 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. Dec 15, 2011 at 17:43
  • 9
    Is there a way to do it only for failed cases? Aug 23, 2012 at 5:54
  • 6
    It's worth noting that HtmlUnitDriver doesn't implement TakesScreenshot (see selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/… for a list of supported drivers). But you can save as HTML.
    – Wernight
    Jul 12, 2013 at 10:28
  • 10
    What package is required to import for using FileUtils class? Apr 10, 2014 at 6:20
  • 11
    @RiponAlWasim probably org.apache.commons.io.FileUtils
    – Ben
    Jul 31, 2014 at 15:25
314

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.

9
  • For other browsers, exchange the webdriver instance. If you just want screenshots of your website including state, have a look at Usersnap.
    – Gregor
    Aug 22, 2013 at 13:04
  • @DavidRöthlisberger thats all great, but your comment has nothing to do with my answer Feb 26, 2017 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: stackoverflow.com/questions/37906704/… Mar 2, 2017 at 12:41
  • 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! Nov 28, 2017 at 10:57
  • 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 5, 2019 at 18:41
118

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;
    }
}
6
  • 10
    Works perfectly. Caveat: takes a screen shot not a page shot.
    – ljgww
    Apr 23, 2015 at 7:15
  • do you mean it gets desktop and everything? Or you mean that it just gets the viewport?
    – vtortola
    Mar 1, 2017 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, 2017 at 19:50
  • 3
    update to SaveAsFile(string path, ScreenshotImageFormat format) ScreenshotImageFormat.Jpeg
    – Kieran
    Aug 1, 2017 at 2: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, 2019 at 16:15
85

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);
   });
});
3
  • 3
    Similar to how Browserstack describes it: browserstack.com/automate/node#enhancements-screenshots Dec 24, 2013 at 7:40
  • in data.replace what exactly are you doing in the parenthesis? Apr 6, 2015 at 7: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, 2016 at 1:21
70

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.

5
  • 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 6, 2011 at 22:33
  • 2
    Is there any way to take the full page screenshot, not just the visible area? Aug 28, 2014 at 6:38
  • 2
    Full page is taken by default. At least using headless and Firefox
    – Ashley
    Feb 17, 2015 at 9:59
  • Why parentheses for driver.save_screenshot, but not for driver.get? Nov 5, 2020 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, 2020 at 0:53
36

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
2
  • 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 6, 2013 at 17:42
  • 1
    I would like to point it out that only this solution worked for me using headless ChromeDriver
    – rado
    Oct 10, 2018 at 0: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');
    }
    ...
}
1
  • 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 Jul 7, 2016 at 12:19
30

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);
}
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;
}
2
  • what driver did you use ? new Augmenter().augment(driver);
    – kozla13
    Jun 28, 2017 at 19:55
  • An explanation would be in order. You can edit your answer (without "Edit:", "Update:", or similar). Nov 5, 2020 at 22:05
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"))
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.

1
  • Your focus should remain on the browser all the time, else takes snapshot of whatever is currently focused. May 11, 2017 at 14:05
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);
}
5
  • 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, 2015 at 16:23
  • Did you try the code? It worked when I last tried it.
    – Erki M.
    Nov 27, 2015 at 8: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, 2015 at 8: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, 2016 at 5: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. Apr 12, 2021 at 2: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.

4

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
1
  • Probably better to use [OpenQA.Selenium.ScreenshotImageFormat]::Png than System.Drawing namespace.
    – Adarsha
    May 22, 2017 at 19:00
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);
}
0
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);
   }
}
4

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

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
2
  • What language is this?
    – codygman
    Sep 19, 2013 at 0:04
  • This looks like its in ruby, not using any any specific web driver
    – James
    May 9, 2014 at 20:30
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
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));
    }
  }
2
  • 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. Feb 26, 2016 at 3: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, 2018 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?

1
  • Nowadays I wouldn't do it this way. I would use a framework like Selenide probably.
    – djangofan
    Jul 12, 2016 at 16:22
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));
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.

2

Selenese

captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
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.

1
  • 4
    this answer is a duplicate that was posted several years after the original Python answer. Dec 12, 2016 at 18:54
2

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

Examples of tests.

0
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);
    }
2
  • "using System.Drawing.Imaging;" assembly.
    – ArNumb
    Jan 22, 2017 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"); Jun 27, 2019 at 9: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();
      }
   }
1
  • If you found this (or any) answer helpful, please upvote it. If this answered your question, please mark it as the accepted answer. Thanks! Apr 1, 2017 at 19:50
1

C# (Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}
1
1

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.