Redeem Now
Read More
Read now
Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    Screenshot with Timestamp in Selenium Webdriver.

    Here we gonna see how to capture a screenshot. Capturing a screenshot is very important thing because at times there are failures on pages as well as to keep evidence of test result we need to take screenshot of that test case.

    Capturing screenshot is little tricky thing in Webdriver because there is no straight forward method that says driver.captureScreenshot.
    But there is an interface called as takesscreenshot which we will use along with one method named as getScreenshotAs().

    Once the screenshot is captured you need to move this file to particular location.
    We will be doing it with the help of one of class called as FileHandler.copyFIle(srcFile, destFile).

    *scrFile is your screenshot file.

    *destFile, you will be creating it with new file and store it into the location where you want.

    This is how we will be capturing screenshot. But before moving ahead we have to specify fileName.

    Since we want every time a new file should be generated.

    So for that we will be implementing time stamp as bellow.

    There is class in java called as Date, lets create an object of this class.

    So it will return current system date along with time, but here we have to replace”:” and “space” because this thing is not supported in the file name. so for this we will convert this into string , then we will call replace method and concatenate .png .

    So now file name will be different every time.

    Hence complete code looks like

    But instead of writing same code every time why not lets create a utility for this as below

    The benefit of doing this is wherever we wanna capture screenshot instead of giving complete thing we will use only captureScreenshot().

    Here’s the Sample code

    Thanks for reading this blog!

    Happy testing!!!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


  • simran
    hi great code.. I was trying to add the methodname(if it fails) along with the TimeStamp screenshot . Can you suggest? thanks
    • Bhanu (Moderator)
      In order to get screenshot on each test failure you need to implement one interface i.e. ITestListener which contains multiple methods and one of those is onTestFailure(ITestResult arg0).
      You can follow bellow steps-
      create a Listener class > implement ItestListener > under ontestFailure method, write code to take screenshot or call capturescreenshot() method in case you have written in any util class further add a Listener in testng.xml file in order to invoke this Listener.
  • Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again