Time to do something a bit more useful using Selenium WebDriver. Taking screenshots as we cycle through our web pages has obvious advantages for unit testing. Firstly we can just run an application overnight, have it visit every page on our website, and review the screenshots for obvious bugs the next morning before releasing to QA. Secondly, we can screenshot our localized websites, and have them linguistically reviewed, or hand off the English screenshots to our translators to provide context during the translation process.
Taking screenshots with WebDriver is exceptionally easy. The thing I like about it most, is that it takes a screenshot of just the area of the browser in which the content resides – no IE/FF/Chrome toolbars etc. But, it also takes the entire webpage – even content not visible on the screen at that time. This is a great feature. I’ve had the problem in the past with long web pages, ones for example that contain a EULA or other long document, where the screenshots had to be taken at intervals as the page scrolled. Obviously not the best process, and not very reusable code.
As mentioned in a previous post, I’m using the Selenium Client Driver for C#. I’ve created a library into which I’m adding useful functions like taking screenshots etc.
The code to take a screenshot is not complex:
using OpenQA.Selenium.IE; using OpenQA.Selenium; using System.Drawing.Imaging; public void TakeScreenshot(IWebDriver driver, string saveLocation) { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); screenshot.SaveAsFile(saveLocation, ImageFormat.Png); }
The libraries referenced can be found in the Selenium Client Driver for C# package which can be downloaded from the Selenium website. These will need to be added to your C# project.
Notice in the above function we pass an ‘IWebDriver’ Object, as opposed to a specific InternetExplorerDriver, FirefoxDriver etc. This means this function can be used regardless of which browser you are dealing with.
Using the function is also a trival matter. Let’s browse to Google and take a screenshot, saving it in the root of the ‘C:\’ drive:
IWebDriver driver = new InternetExplorerDriver(); driver.Navigate().GoToUrl("http://www.google.com"); TakeScreenshot(driver, @"C:\screenshot.png");
Note that the TakeScreenshot function can be customized to use any image format – in fact it should probably be a function parameter. I chose PNG simply because of the small size of the generated image.