如何在Grid上使用多个实例处理Selenium屏幕截图?

时间:2013-08-31 20:40:32

标签: selenium webdriver selenium-webdriver selenium-grid

如何处理在Grid上运行的多个实例的Selenium屏幕截图?假设我有一个Grid Hub驱动网格节点,其中3个Firefox浏览器同时在一台节点机器上运行,如何从3个节点线程中获取3个截然不同的屏幕截图

例如,请将此代码段用于单线程测试:

RemoteWebDriver driver;
driver = new RemoteWebDriver(new URL("http://127.1/wd/hub"), DesiredCapabilities
    .firefox() );
driver.get( "http://www.google.com/" );
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = (TakesScreenshot)augmentedDriver.getScreenshotAs(OutputType
    .FILE);
System.out.println( "Page title is: " + driver.getTitle() );
System.out.println( "Screenshot is located at: " + screenshot.getAbsolutePath());
assertTrue( "Page did not contain string.", driver.getSource().contains( 
    "search") );
driver.quit();

4 个答案:

答案 0 :(得分:4)

它绝对可以。

屏幕截图实际上是特定驱动程序实例的图像,而不是遗传桌面图像。您不会在每个屏幕截图中看到多个浏览器

答案 1 :(得分:2)

以下是我的Utiility代码中的一个片段,它完美无缺

  String path = null;
try {
        File source = ((TakesScreenshot)
                driver).getScreenshotAs(OutputType.FILE);
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy/MMM/dd HH:mm:ss");
        String dateN = formatter.format(currentDate.getTime()).replace("/","_");
        String dateNow = dateN.replace(":","_");
        String snapShotDirectory = Files.screenShotDirectory  + dateNow;

        File f = new File(snapShotDirectory);
        if(f.mkdir()){
        path = f.getAbsolutePath() + "/" + source.getName();
        FileUtils.copyFile(source, new File(path)); 
        }
    }
    catch(IOException e) {
        path = "Failed to capture screenshot: " + e.getMessage();
    }

您可以尝试使用它。

答案 2 :(得分:1)

首先,Selenium/WebDriver/Selenium Grid不会为您处理多线程,它的底层测试框架(TestNG/JUnit/Cucumber等)会处理它。 WebDriver不是线程安全的,如果您并行运行测试,则需要确保代码是线程安全的。

回到你的问题,你写的代码会覆盖在同一个截图文件中。您需要使用其他名称将文件复制到其他位置。我建议你在屏幕截图文件前加上毫秒精度的时间戳,然后复制截屏文件。这样,您可以为三个不同的浏览器实例提供三个独特的不同屏幕截图。这对我来说过去很有用。

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String file_name = "screenshot_"+ Add system_time with millisecond precision 
FileUtils.copyFile(scrFile, new File(file_name));

答案 3 :(得分:0)

捕获您需要使用其他名称将文件复制到其他位置的屏幕截图。以下代码对您有所帮助。

创建任何名称的方法。我在这里创建了captureScreenshot方法。

 public static void captureScreenshot(String path) throws IOException{
    try{
        File scrFile= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        FileUtils.copyFile(scrFile, new File(path) );
    }
    catch (Exception e){
        System.out.println("Failed to capture screenshot");
   }

}

然后在您想要截取屏幕截图的方法中使用此方法。请参阅以下代码行。这里我使用系统当前时间(以毫秒为单位)来保存具有不同名称的多个图像。

captureScreenshot("././screenshots/loginerror_" + System.currentTimeMillis()+".jpg");