Take Screenshots With RemoteWebDriver

So am currently working on a project that I intend to post about soon, and ran into an issue when trying to take screenshots using RemoteWebDriver.
Turns out that RemoteWebDriver doesn't have the capability that the other drivers have, however after a few searches I managed to find a solution and with a small tweak got it working.

So here is how you can take screenshots using RemoteWebDriver.

You need to create a class that extends RemoteWebDriver and inherits ITakeScreenshot, should look like this:



The issue I had was that the example I found by Jim Evans, must have been when RemoteWebDriver didn't have any paramters, so had to include the URI and Capabilities.

To use this now you have to use your ScreenShotRemoteWebDriver instead of RemoteWebDriver, like so:



Then you can take a screenshot using the following code:


Note that the screenshots are saved on the machine where the test is being executed from, not the client.

Happy screenshoting!

* Update *

There has been lots of changes in RemoteWebDriver since I wrote this original post, one of those is that screenshots are now a lot easier as per Jan Zdrahal comment below.

So you can now create an extension for IWebDriver to take a screenshot for you that will also work with RemoteWebDriver.

Then you can call the method like so.

4 comments:

  1. Hi,

    Just wondering if it is worth protecting the call to the driver in GetScreenshot() in a try, catch block in case it fails?

    We have implemented something similar to log screens when the test fails, and found that on one occasion the driver failed to take a screenshot - however we still wanted to proceed to log other diagnostic information.

    Cheers,
    Martin

    ReplyDelete
  2. Perhaps, or potentially even wrap the whole screenshot block in try / catch instead of the call to the driver. That way you can capture if the call fails but also if the write to the file system fails.

    Yes i do the same using NUnit, if the test result is anything other than "Passed" take a screenshot.

    Will have a think about that, thanks for the comment.

    ReplyDelete
  3. just wondering why did you use this statement "byte[] screenshotAsByteArray = ss.AsByteArray;" in this below code
    Screenshot ss = ((ITakesScreenshot)webDriver).GetScreenshot();
    string screenshot = ss.AsBase64EncodedString;
    byte[] screenshotAsByteArray = ss.AsByteArray;
    ss.SaveAsFile(@"C:\Temp", System.Drawing.Imaging.ImageFormat.Jpeg);

    ReplyDelete
  4. Hi,

    Instead of the last piece of code I just used this:

    ((ITakesScreenshot)WebDriver).GetScreenshot().SaveAsFile("homepage.png", ImageFormat.Png);

    And it seems to work. :)

    panjan

    ReplyDelete