2016-12-02 82 views
0

我想使用java在selenium中使用多个屏幕截图。
例如,我正在尝试导航我网站中的所有链接。在导航过程中,如果有错误(例如未找到页面,服务器错误),我想单独捕获截图中的所有错误。目前它正在压倒前一个。如何通过使用java的selenium webdriver捕获多个屏幕截图(不是覆盖以前的屏幕截图)

if(driver.getTitle().contains("404")) 
{ 
    System.out.println("Fail"); 
     File scrFile = (TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
     try { 

      FileUtils.copyFile(scrFile, new File("outputfile")); 
      }catch(IOException e){ 

       e.printStackTrace(); 
     } 

     } 

      else 

      { 

      System.out.println("Pass"); 

      } 
+3

你的问题是什么?如何创建截图;或者如何提出一个命名合理的命名方案? – GhostCat

+0

我的问题是如何创建多个屏幕截图,我已经设法得到屏幕截图,但我不想更新上一​​屏幕截图 – Prakash

+2

你看,这就是我的意思是**命名**方案。您正在覆盖您的屏幕快照,因为您始终使用相同的**名称**作为文件。因此:你应该想出一种使这些文件名具有唯一性的方法,并且可能“告诉”(以便文件名告诉你它被采用的路径)。 – GhostCat

回答

0

我会做一些事情来清理这个过程。

  1. 把你的屏幕截图代码放到一个函数中。

  2. 将日期时间戳记添加到您的屏幕截图文件名。这将给每个文件一个唯一的名称。

  3. 向截图文件名添加一个简短的错误字符串。这将使您能够快速查看每种错误类型的存在情况。奖励点数用于为每种错误类型创建一个文件夹,并只在该文件夹中放置该特定错误的屏幕截图。

您的脚本看起来像

String imageOutputPath = "the path to the folder that stores the screenshots"; 
if (driver.getTitle().contains("404")) 
{ 
    takeScreenshotOfPage(driver, imageOutputPath + "404 error " + getDateTimeStamp() + ".png"); 
} 
else if (some other error) 
{ 
    takeScreenshotOfPage(driver, imageOutputPath + "some other error " + getDateTimeStamp() + ".png"); 
} 
else if (yet another error) 
{ 
    takeScreenshotOfPage(driver, imageOutputPath + "yet another error " + getDateTimeStamp() + ".png"); 
} 

和功能,采取截图

public static void takeScreenshotOfPage(WebDriver driver, String filePath) throws IOException 
{ 
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); 
    BufferedImage srcImage = ImageIO.read(srcFile); 
    ImageIO.write(srcImage, "png", new File(filePath)); 
} 

和功能,使文件名友好日期时间戳

public static String getDateTimeStamp() 
{ 
    // creates a date time stamp that is Windows OS filename compatible 
    return new SimpleDateFormat("MMM dd HH.mm.ss").format(Calendar.getInstance().getTime()); 
} 

你会最终结束w第i个是像下面这样的文件名,它们按错误类型整齐排序,每个文件名都有唯一的文件名。

404 error Dec 02 13.21.18.png 
404 error Dec 02 13.22.29.png 
404 error Dec 02 13.22.39.png 
some other error Dec 02 13.21.25.png 
some other error Dec 02 13.22.50.png 
some other error Dec 02 13.22.56.png 
yet another error Dec 02 13.21.34.png 
yet another error Dec 02 13.23.02.png 
yet another error Dec 02 13.23.09.png 
+0

您当然可以通过更改'SimpleDateFormat()'中的格式将日期时间戳修改为任何您想要的格式。如果你把关于它的页面的信息或者点击的链接或者其他任何信息放在这里,这将会更加有用。您最好记录下关于页面,链接等的大量信息,然后引用相应屏幕截图的文件名。 – JeffC

+0

谢谢Jeffc为您详细的脚本,我已经使用你的逻辑与一些小的变化,其作品伟大 – Prakash

1

要停止覆盖输出文件,您必须为每个屏幕截图指定一个唯一的名称。
某处在代码,创建计数器

int counter = 1; 

然后

FileUtils.copyFile(scrFile, new File("outputfile" + counter)); 
counter++; 

所以柜台给每个的CopyFile后的目标文件不同的名称。

+1

你可以添加一些提示来将信息添加到文件名,关于错误路径或这样的事情。只需要记录文件肯定会有所帮助,但最终会给他带来很多无关紧要的文件名称。 – GhostCat

+0

是的,它只是计算文件,有近800页,所以我们不知道它们中有多少是破损页面,所以很难为每个屏幕截图提供一个唯一的名称 – Prakash

+0

这种方法没有提到的缺点是,如果你再次运行该脚本,它将覆盖这些屏幕截图。您甚至可能会因最后一次运行和这次运行的混合而失败,具体取决于采取了多少次新的屏幕截图。 – JeffC