如何使用Java通过Selenium Webdriver捕获多个屏幕截图(不覆盖上一张)



我想使用java在硒中进行多个屏幕截图。
例如,我正在尝试浏览网站中的所有链接。在导航时,如果存在错误(例如找不到页面,服务器错误),我想单独捕获屏幕截图中的所有错误。目前,它覆盖了上一个。

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");
            }

要停止覆盖输出文件,您必须给每个屏幕截图一个唯一的名称。
代码中的某个地方,创建计数器

int counter = 1;

然后

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

因此,计数器在每个CopyFile之后给目标文件提供了不同的名称。

您可以使用当前日期时间戳记,并使用图像格式

附加此图章

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

  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());
}

您最终将获得的文件名之类的类似于以下的文件名,它们通过错误类型整齐排序,每个都带有唯一的文件名。

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

相关内容

最新更新