How can I take a screenshot with Selenium WebDriver?

后端 未结 30 2659
不知归路
不知归路 2020-11-21 07:48

Is it possible to take a screenshot using Selenium WebDriver?

(Note: Not Selenium Remote Control)

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 08:36

    Java

    A method to capture a screenshot for the failures in Selenium with TestName and Timestamp appended.

    public class Screenshot{
        final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
        public static String imgname = null;
    
        /*
         * Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
         */
        public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
          try {
          String imgpath = System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
          File f = new File(imgpath);
          if(!f.exists())   {
              f.mkdir();
            }
            Date d = new Date();
            SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
            String timestamp = sd.format(d);
            imgname = imgpath + "\\" + timestamp + ".png";
    
            // Snapshot code
            TakesScreenshot snpobj = ((TakesScreenshot)wb);
            File srcfile = snpobj.getScreenshotAs(OutputType.FILE);
            File destFile = new File(imgname);
            FileUtils.copyFile(srcfile, destFile);
    
          }
          catch(Exception e) {
              e.getMessage();
          }
       }
    

提交回复
热议问题