C# WebDriver extension: Driver.TakeScreenshot

I was having a chat to a colleague this week about how Watir in Ruby is much nicer than WebDriver in other languages because it provides a lot more functionality without any work, such as screenshots, waiting etc. I hadn’t really thought about that for a while because, despite working predominantly in C#, I have a collection of WebDriver and WebElement extensions I have written which make it much easier to use.

I plan to write a series of short posts sharing a different extension method in each one.

I previously shared these:

  • IWebElement.Set(text)
  • SelectElement.SelectBySubText(subText)
  • IWebElement.FindVisibleElement(by)
  • IWebElement.VisibleElementExists(by)

Today I will share IWebDriver.TakeScreenshot(prefix). This method allows you to easily take a timestamped screenshot of what is displayed in the browser with an optional prefix to the filename.

using System;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace WebDriverExtensions
{
    public static class WebElementExtensions
    {
        public static string TakeScreenshot(this IWebDriver driver, string prefix)
        {
            var fileName = String.Format("{0}{1}{2}", prefix, DateTime.Now.ToString("HHmmss"), ".png");
            var screenShot = ((ITakesScreenshot)driver).GetScreenshot();
            screenShot.SaveAsFile(fileName, ImageFormat.Png);
            return fileName;
        }
    }

    [TestClass]
    public class ExtensionUnitTests
    {
        [TestMethod]
        public void TakeScreenShot()
        {
            var driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("data:text/html,Some Text");
            var fileName = driver.TakeScreenshot("myScreenShot");
            Assert.IsTrue(File.Exists(fileName));
            driver.Quit();
        }
    }
}

2 thoughts on “C# WebDriver extension: Driver.TakeScreenshot

  1. Specflow users can use ScenarioInfo.Title from ScenarioContext as prefix in filename to save screenshots using test name.

  2. Hello Alister, I very much enjoyed your topic and I find it very useful, clear and well written, congrats on that :). I have a challenge for you – do you think you could provide some information about automation based on finding specific image on the screen in let’s say a flash application or anywhere you can’t use element.FindBy(). I searched some solutions for this and they all seem to use unmanaged code to produce the mouse clicks and pixel by pixel comparison of the let’s say pattern image we are looking for and the image that’s being scanned. And this is slooow. So my question is do you think there’s some optimizations for that and could you post something about it? Thanks in advance :)

Comments are closed.