Ruchi Dhole
Ruchi Dhole

Reputation: 95

Taking Screen shots on specific error page in selenium web driver

My scenario is, I'm getting same error page on many of my button clicks on the site. I want to take screenshots, of this same error page, with reference on which link of the site this error page occured. So I want screenshot whenever this error page occurs on any click. Can you suggest me how to write the function for this and how to call that function in some other function in selenium Webdriver. Please share some code sample for that.

As of currently, I'm writing it only as :

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  FileUtils.copyFile(scrFile, new File("D:\\Home\\Ruchi\\failure.png"));

But in this I need to write these lines of code after every failure occurrence.

Upvotes: 2

Views: 1751

Answers (1)

Shubham Jain
Shubham Jain

Reputation: 17553

use try and catch block

try{
  // Put your script here
}
catch(Exception ex)
{
            File scrn=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

            // extracting date for folder name.
            SimpleDateFormat sdfDate1 = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
            Date now1 = new Date();
            String strDate1 = sdfDate1.format(now1);

            // extracting date and time for snapshot file
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//dd/MM/yyyy
            Date now = new Date();
            String strDate = sdfDate.format(now);

            String filefolder="./Snap/"+strDate1+"/";  // create a folder as snap in  your project directory

            // Creating folders and files
            File f = new File(filefolder+strDate+".jpeg");

            FileUtils.copyFile(scrn, new File(f.getPath()));
}

If your script fails then the program jumps to catch block and then code will take screen shot for you

Hope it will help you :)

Upvotes: 1

Related Questions