51

I need a way to take screenshots of my functional tests. Right now I'm using Selenium 2 with C# bindings. I pretty much want to take a screenshot at the end of the test to make sure the desired page is displayed. Are there any particular tools you guys know of that I can incorporate into my C# code that will trigger a screenshot? I couldn't find a built-in Selenium 2 solution (without looking it over).

ballade4op52
  • 2,142
  • 5
  • 27
  • 42
James
  • 5,622
  • 9
  • 34
  • 42

13 Answers13

75

To do screenshots in Selenium 2 you need to do the following

driver = new FireFoxDriver(); // Should work in other Browser Drivers
driver.Navigate().GoToUrl("http://www.theautomatedtester.co.uk");
Screenshot ss = ((ITakesScreenshot) driver).GetScreenshot();

//Use it as you want now
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile("filename", ImageFormat.Png); //use any of the built in image formating
ss.ToString();//same as string screenshot = ss.AsBase64EncodedString;

That code should work, as I quickly tested it in IronPython Repl. See the IronPython code below

import clr
clr.AddReference("WebDriver.Common.dll")
clr.AddReference("WebDriver.Firefox.dll")
from OpenQA.Selenium import *
from OpenQA.Selenium.Firefox import *
driver = FirefoxDriver()
driver.Navigate().GoToUrl("http://www.theautomatedtester.co.uk")
s = driver.GetScreenshot()
s.AsBaseEncodedString
# HUGE string appears in the REPL
ballade4op52
  • 2,142
  • 5
  • 27
  • 42
AutomatedTester
  • 22,188
  • 7
  • 49
  • 62
  • Thanks! So I have the string for the filename "C:\\..path..\\screen.png", but it never appears there. – James Jul 29 '10 at 16:43
  • 1
    Replace this code above: "Screenshot ss = driver.GetScreenshot();" ...with this code: "Screenshot ss = ((ITakesScreenshot)webDriver).GetScreenshot();" – JustBeingHelpful Feb 02 '12 at 17:59
  • 1
    If using .NET 4.0 and Selenium .NET 4.0 drivers, you will need to explicitly add a reference to System.Drawing (Add Reference > .NET tab > System.Drawing) if you created your class library project in Visual Studio 2010 ... then call this to save the file somewhere: "ss.SaveAsFile(@"C:\ss.png", System.Drawing.Imaging.ImageFormat.Png);" – JustBeingHelpful Feb 02 '12 at 18:05
  • If your running on Grid, you will have to use the Augmenter class. – djangofan Aug 07 '13 at 19:59
  • 5
    ImageFormat.Png is now deprecated, use ScreenshotImageFormat.Png instead – Samuel Rondeau-Millaire Feb 27 '17 at 22:14
32
var driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
var ss = driver.GetScreenshot();   
ss.SaveAsFile("ss.png", System.Drawing.Imaging.ImageFormat.Png);
Toolkit
  • 10,779
  • 8
  • 59
  • 68
13

I don't know if it matters, but I ended up having to cast the driver when i was writing in c#.

something like:

Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
user800612
  • 169
  • 2
  • 9
6

Just use the extension method TakeScreenshot() in one line of code.

IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("Your_Homepage_Url");

driver.TakeScreenshot().SaveAsFile("file_name_string", ImageFormat.Jpeg);
Deeb
  • 307
  • 5
  • 6
  • 4
    Note that the `TakeScreenshot()` method is an extension method that requires the `Selenium.Support` NuGet package to be installed. – thecodefish Mar 30 '16 at 20:35
  • @Deeb ```ImageFormat``` now is deprecated use ```ScreenshotImageFormat``` instead. – TotPeRo Aug 02 '17 at 07:17
3
  1. Add a reference of System.Drawing in your solution/project.
  2. Use System.Drawing.Imaging namespace in your test.

Here I am capturing the screen shot of Facebook Home page.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using System.IO;
using System.Collections;
using System.Drawing.Imaging;

namespace FacebookRegistrationUsingC_Sharp
{
    [TestFixture]
    public class ScreenShot
    {
        IWebDriver driver = null;
        IWebElement element = null;

        [SetUp]
        public void SetUp()
        {
            driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32");           
            driver.Navigate().GoToUrl("https://www.Facebook.com");
            driver.Manage().Window.Maximize();

        }
        [Test]
        public void TestScreenShot()
        {           

            Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
            ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        [TearDown]
        public void TearDown()
        {
            driver = null;
            element = null;
        }
    }
}
Lachlan Goodhew-Cook
  • 1,101
  • 17
  • 31
Avinash Pande
  • 1,510
  • 19
  • 17
1
public void TakeScreenshot(string saveLocation) {
        var location = GetPath() + _name + "\\" + saveLocation + ".png";
        var ssdriver = _driver as ITakesScreenshot;
        var screenshot = ssdriver.GetScreenshot();
        screenshot.SaveAsFile(location, ImageFormat.Png);
    }

This code will help you to take screen shot

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Shekhar
  • 11
  • 1
1

JAVA

protected void fullPageScreenshot(String testname) {
            String timeStamp = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(Calendar.getInstance().getTime());
            String imageName = testname + "-" + timeStamp + ".png";
            Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(2000))
                    .takeScreenshot(DriverManager.getDriver());
            try {
                ImageIO.write(screenshot.getImage(), "PNG", new File("./FullPage_Screenshots/" + imageName));
            } catch (Exception e) {
                System.out.println("Capturing FullPage Screenshot failed");
            }
        }

use Ashot library to take fullpage screenshots - even where pages needs to be scrolled https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot/1.5.4

Rahul Rana
  • 41
  • 6
0

Use System.Drawing.Imaging reference. Following code can be used for taking screenshot.

IWebDriver driver = new FirefoxDriver();
ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
String fp = "D:\\" + "snapshot" + "_"+ DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt") + ".png";
screenshot.SaveAsFile(fp, ImageFormat.Png);

Notes: Timestamp has two advantages: 1) You'll get to know the perfect DateTime when screenshot is taken. 2) SaveAsFile function overwrites the existing file. So, DateTime can help for different file creation.

0
        ScreenCaptureJob scj;
        scj = new ScreenCaptureJob();
        // Specify the path & file name in which you want to save         
        scj.OutputScreenCaptureFileName = @"C:\Users\jpavankumar\Desktop\Screencaptuere\ScreenRecording4.wmv";
        // Start the Screen Capture Job
        scj.Start(); scj.Stop();

Try this code out here ... hope it will be useful to you .... !

  • Please explain your answer covering exactly how this approach achieves the desired output and why it will work for. This would really help the OP's knowledge. – Bluetree Nov 20 '17 at 11:47
0
driver.Url = "https://www.amazon.in/";
//Store image in bin folder
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile("CurrentPage.png"); 
//Store image in D drive        
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(@"D:\CurrentPage.png");
Zoe
  • 27,060
  • 21
  • 118
  • 148
0

Define this in global code :

var counter = DateTime.Now.Ticks.ToString();

((ITakesScreenshot)driver).GetScreenshot().SaveAsFile((snap +counter + ".jpg").ToString(), OpenQA.Selenium.ScreenshotImageFormat.Jpeg);
test.Log(LogStatus.Fail, "Snapshot below: " + test.AddScreenCapture(snap + counter + ".jpg"));
vvvvv
  • 25,404
  • 19
  • 49
  • 81
0

Best way to take screenshot and store in the file location in a generic way in python :

def screenShots(self):
        fileName= NewFile + "." + str(round(time.time() * 1000)) + ".png"
        screenshotDirectory = "../screenshot/"  #Move to that directory where you want ot store the screenshot
        relativeFileName = screenshotDirectory + fileName
        currentDirectory = os.path.dirname(__file__)
        destinationFile = os.path.join(currentDirectory,relativeFileName)
        destinationDirectory = os.path.join(currentDirectory,screenshotDirectory)

        try:
            if not os.path.exists(destinationDirectory):
                os.makedirs(destinationDirectory)
            self.driver.save_screenshot(destinationFile)

            self.log.info("Screenshot saved to directory" + destinationFile)

        except:
            self.log.error("Exception Occured")
            print_stack()
Jayesh Babu
  • 1,389
  • 2
  • 20
  • 34
-1

Using selenium there were two calls I was familiar with: captureEntirePageScreenshot and captureScreenshot. You might want to look into those calls to see if they'll accomplish what you're after.

Abel
  • 56,041
  • 24
  • 146
  • 247
Bobby B
  • 2,372
  • 3
  • 24
  • 31