Java 类org.openqa.selenium.TakesScreenshot 实例源码

项目:bdd-test-automation-for-mobile    文件:SetupTeardownSteps.java   
@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            logger.info("Test failed, taking screenshot");
            byte[] screenshot = ((TakesScreenshot) new Augmenter().augment(getAppiumDriver()))
                    .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        }
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }
    application.tearDown();
}
项目:marathonv5    文件:JavaDriverTest.java   
public void screenshot() throws Throwable {
    try {
        driver = new JavaDriver();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
        if (driver instanceof TakesScreenshot) {
            Thread.sleep(1000);
            File screenshotAs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            System.out.println(screenshotAs.getAbsolutePath());
            Thread.sleep(20000);
        }
    } finally {
        JavaElementFactory.reset();
    }
}
项目:Gospy    文件:SeleniumDemo.java   
public static void main(String[] args) {
    String phantomJsPath = "D:/Program Files/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe";
    String savePath = "D:/screenshot.png";
    Gospy.custom()
            .setScheduler(Schedulers.VerifiableScheduler.custom()
                    .setPendingTimeInSeconds(60).build())
            .addFetcher(Fetchers.TransparentFetcher.getDefault())
            .addProcessor(Processors.PhantomJSProcessor.custom()
                    .setPhantomJsBinaryPath(phantomJsPath)
                    .setWebDriverExecutor((page, webDriver) -> {
                        TakesScreenshot screenshot = (TakesScreenshot) webDriver;
                        File src = screenshot.getScreenshotAs(OutputType.FILE);
                        FileUtils.copyFile(src, new File(savePath));
                        System.out.println("screenshot has been saved to " + savePath);
                        return new Result<>();
                    })
                    .build())
            .build().addTask("phantomjs://http://www.zhihu.com").start();
}
项目:zucchini    文件:ScreenshotHook.java   
public static void createScreenshot(String fileName) {

        if (SeleniumDriver.getInstance() instanceof TakesScreenshot) {

            File fileSrc = ((TakesScreenshot) SeleniumDriver.getInstance()).getScreenshotAs(OutputType.FILE);

            try {
                File destFile = new File(String.format(SCREENSHOTS_FORMAT, fileName));
                FileUtils.copyFile(fileSrc, destFile);
                LOG.info("[Screenshot] " + destFile.getAbsolutePath());
            } catch (IOException e) {
                ;
            }
        }

    }
项目:vaadin-016-helloworld-14    文件:WebDriverFunctions.java   
static Consumer<WebDriver> takeScreenShot() {
    return (webDriver) -> {
        //take Screenshot
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            outputStream.write(((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES));
            //write to target/screenshot-[timestamp].jpg
            final FileOutputStream out = new FileOutputStream("target/screenshot-" + LocalDateTime.now() + ".png");
            out.write(outputStream.toByteArray());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
}
项目:Cognizant-Intelligent-Test-Scripter    文件:SeleniumDriver.java   
public File createScreenShot() {
    try {
        if (driver == null) {
            System.err.println("Report Driver[" + runContext.BrowserName + "]  is not initialized");
        } else if (isAlive()) {
            if (alertPresent()) {
                System.err.println("Couldn't take ScreenShot Alert Present in the page");
                return ((TakesScreenshot) (new EmptyDriver())).getScreenshotAs(OutputType.FILE);
            } else if (driver instanceof MobileDriver || driver instanceof ExtendedHtmlUnitDriver
                    || driver instanceof EmptyDriver) {
                return ((TakesScreenshot) (driver)).getScreenshotAs(OutputType.FILE);
            } else {
                return createNewScreenshot();
            }
        }
    } catch (DriverClosedException ex) {
        System.err.println("Couldn't take ScreenShot Driver is closed or connection is lost with driver");
    }
    return null;
}
项目:willtest    文件:ScreenshotRule.java   
@Override
protected void onError(Description description, Throwable testFailure) throws Throwable {
    super.onError(description, testFailure);
    if(Objects.nonNull(screenshotProvider)) {
        WebDriver webDriver = seleniumProvider.getWebDriver();
        if (webDriver instanceof TakesScreenshot) {
            BufferedImage screenshot = screenshotProvider.takeScreenshot(webDriver);

            File destFile = TestReportFile.forTest(description).withPostix(".png").build().getFile();
            ImageIO.write(screenshot, "PNG", destFile);

            LOGGER.info("Saved screenshot as " + destFile.getAbsolutePath());
        } else {
            testFailure.addSuppressed(
                    new RuntimeException(
                            "Could not take screenshot, since webdriver is not a " +
                                    TakesScreenshot.class.getName() + " instance as expected. Actual class is " +
                                    webDriver.getClass().getName()));
        }
    } else {
        LOGGER.info("Due to SreenshotProvider is not specified, no screenshot is taken");
    }
}
项目:POM_HYBRID_FRAMEOWRK    文件:ReportManager.java   
private static String captureScreenshot(WebDriver driver, String screenshotPath, String ScreenshotName) {

        String destinationPath = null;
        try {
            File destFolder = new File(screenshotPath);

            destinationPath = destFolder.getCanonicalPath() + "/" + ScreenshotName + ".png";

            // Cast webdriver to Screenshot
            TakesScreenshot screenshot = (TakesScreenshot) driver;

            File sourceFile = screenshot.getScreenshotAs(OutputType.FILE);

            FileUtils.copyFile(sourceFile, new File(destinationPath));

        } catch (Exception e) {
            System.out.println("Error capturing screenshot...\n" + e.getMessage());
            e.printStackTrace();
        }
        return destinationPath;
    }
项目:Actitime-Framework    文件:ReportNGReport.java   
/**
 * This method captures a screenshot
 **/
public static void captureScreenshot(WebDriver driver, String screenshotName) {
    try {
        TakesScreenshot ts = (TakesScreenshot) driver;
        File source = ts.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName
                + "_" + strDateStamp

                + ".png"));
        String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
        System.setProperty(ESCAPE_PROPERTY, "false");
        URL path = new File(dirPath + "/ " + screenshotName + "_"
                + strDateStamp + ".png").toURI().toURL();
        String test = "<a href=" + path + "> click to open screenshot of "
                + screenshotName + "</a>";
        Reporter.log(screenshotName + test + "<br>");
        Reporter.log("<br>");
    }

    catch (Exception e) {
        System.out.println("Exception while taking screenshot "
                + e.getMessage());
    }
}
项目:Habanero    文件:ScreenShotHook.java   
/**
 * <p>
 * Takes screen-shot if the scenario fails
 * </p>
 *
 * @param scenario will be the individual scenario's within the Feature files
 * @throws InterruptedException Exception thrown if there is an interuption within the JVM
 */
@After()
public void afterTest(Scenario scenario) throws InterruptedException {
    LOG.info("Taking screenshot IF Test Failed");
    System.out.println("Taking screenshot IF Test Failed (sysOut)");
    if (scenario.isFailed()) {
        try {
            System.out.println("Scenario FAILED... screen shot taken");
            scenario.write(getDriver().getCurrentUrl());
            byte[] screenShot = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenShot, "image/png");
        } catch (WebDriverException e) {
            LOG.error(e.getMessage());
        }
    }
}
项目:mobileAutomation    文件:Driver.java   
/**
 * Save screenshot to file.
 * 
 * @param fileName
 */
public static void saveScreenShot(String fileName){
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    try {

        Path destPath = Paths.get(
                Logger.getLogger().getLogDirPath().toString() 
                + "/" + fileName);

        FileUtils.copyFile(scrFile, new File(destPath.toString()));
        logger.log("Saved screenshot: " + destPath.toString());

    } catch (IOException e) {
        logger.logLines(e.getStackTrace().toString());
        logger.log("Failed to save screenshot!");
        System.out.println();
    }
}
项目:crawler    文件:WindowUtil.java   
public static void taskScreenShot(WebDriver driver,File saveFile){
    if(saveFile.exists()){
        saveFile.delete();
    }
    byte[] src=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);//.FILE);linux下非root用户,java创建临时文件存在问题
    log.info("截图文件字节长度"+src.length);
    try {
        FileUtils.writeByteArrayToFile(saveFile, src);
    } catch (IOException e) {
        e.printStackTrace();
        log.error("截图写入失败",e);
    }
}
项目:GeoCrawler    文件:HttpWebClient.java   
private static void takeScreenshot(WebDriver driver, Configuration conf) {
  try {
    String url = driver.getCurrentUrl();
    File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    LOG.debug("In-memory screenshot taken of: {}", url);
    FileSystem fs = FileSystem.get(conf);
    Path screenshotPath = new Path(conf.get("selenium.screenshot.location") + "/" + srcFile.getName());
    if (screenshotPath != null) {
      OutputStream os = null;
      if (!fs.exists(screenshotPath)) {
        LOG.debug("No existing screenshot already exists... creating new file at {} {}.", screenshotPath, srcFile.getName());
        os = fs.create(screenshotPath);
      }
      InputStream is = new BufferedInputStream(new FileInputStream(srcFile));
      IOUtils.copyBytes(is, os, conf);
      LOG.debug("Screenshot for {} successfully saved to: {} {}", url, screenshotPath, srcFile.getName()); 
    } else {
      LOG.warn("Screenshot for {} not saved to HDFS (subsequently disgarded) as value for "
          + "'selenium.screenshot.location' is absent from nutch-site.xml.", url);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:xlt-visual-assert    文件:VisualAssertion.java   
/**
 * Takes a screenshot if the underlying web driver instance is capable of doing it. Fails with a message only in
 * case the webdriver cannot take screenshots. Avoids issue when certain drivers are used.
 * 
 * @param webDriver
 *            the web driver to use
 * @return {@link BufferedImage} if the webdriver supports taking screenshots, null otherwise
 * @throws RuntimeException
 *             In case the files cannot be written
 */
private BufferedImage takeScreenshot(final WebDriver webDriver)
{
    if (webDriver instanceof TakesScreenshot)
    {
        final byte[] bytes = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES);
        try
        {
            return ImageIO.read(new ByteArrayInputStream(bytes));
        }
        catch (final IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    else
    {
        return null;
    }
}
项目:cashion    文件:Snapshot.java   
public static void snapshot(TakesScreenshot drivername, String filename)
{
    // this method will take screen shot ,require two parameters ,one is driver name, another is file name


  File scrFile = drivername.getScreenshotAs(OutputType.FILE);
      // Now you can do whatever you need to do with it, for example copy somewhere
      try {
          System.out.println("save snapshot path is:"+filename);
          FileUtils.copyFile(scrFile, new File(filename));
      } catch (IOException e) {
          // TODO Auto-generated catch block
          System.out.println("Can't save screenshot");
          e.printStackTrace();
      } 
      finally
      {
          System.out.println("screen shot finished");
      }
}
项目:SeleniumCucumber    文件:GenericHelper.java   
public String takeScreenShot(String name) throws IOException {

        if (driver instanceof HtmlUnitDriver) {
            oLog.fatal("HtmlUnitDriver Cannot take the ScreenShot");
            return "";
        }

        File destDir = new File(ResourceHelper.getResourcePath("screenshots/")
                + DateTimeHelper.getCurrentDate());
        if (!destDir.exists())
            destDir.mkdir();

        File destPath = new File(destDir.getAbsolutePath()
                + System.getProperty("file.separator") + name + ".jpg");
        try {
            FileUtils
                    .copyFile(((TakesScreenshot) driver)
                            .getScreenshotAs(OutputType.FILE), destPath);
        } catch (IOException e) {
            oLog.error(e);
            throw e;
        }
        oLog.info(destPath.getAbsolutePath());
        return destPath.getAbsolutePath();
    }
项目:XPathBuilder    文件:TestBase.java   
@AfterMethod
public void setScreenshot(ITestResult result) {
  if (!result.isSuccess()) {
    try {
      WebDriver returned = new Augmenter().augment(webDriver);
      if (returned != null) {
        File f = ((TakesScreenshot) returned).getScreenshotAs(OutputType.FILE);
        try {
          FileUtils.copyFile(f,
              new File(SCREENSHOT_FOLDER + result.getName() + SCREENSHOT_FORMAT));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (ScreenshotException se) {
      se.printStackTrace();
    }
  }
}
项目:domui    文件:DefaultScreenshotHelper.java   
@Override public boolean createScreenshot(WebDriverConnector wd, File screenshotFile) throws Exception {
    WebDriver ad = wd.driver();

    if(ad instanceof RemoteWebDriver && wd.getDriverType() == WebDriverType.REMOTE) {
        //for remote drivers we need to do augmenter thingy, for local we must not
        ad = new Augmenter().augment(ad);
    }

    if(ad instanceof TakesScreenshot) {
        File f = ((TakesScreenshot) ad).getScreenshotAs(OutputType.FILE);
        try {
            FileTool.copyFile(screenshotFile, f);
        } finally {
            FileTool.closeAll(f);
        }
        return true;
    }
    return false;
}
项目:riot-automated-tests    文件:TestUtilities.java   
public void captureImage(String imgUrl,MobileElement element) throws IOException{
    new File(imgUrl).delete();
    File screen = ((TakesScreenshot) appiumFactory.getAndroidDriver2())
            .getScreenshotAs(OutputType.FILE);
    Point point = element.getLocation();

    //get element dimension
    int width = element.getSize().getWidth();
    int height = element.getSize().getHeight();

    BufferedImage img = ImageIO.read(screen);
    BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width,
            height);
    ImageIO.write(dest, "png", screen);
    File file = new File(imgUrl);
    FileUtils.copyFile(screen, file);
}
项目:riot-automated-tests    文件:RiotMiscTests.java   
@Test(groups="1driver_android")
public void takeScreenShot() throws Exception{
    // Set folder name to store screenshots.
    destDir = "screenshots";
    // Capture screenshot.
    File scrFile = ((TakesScreenshot) appiumFactory.getAndroidDriver1()).getScreenshotAs(OutputType.FILE);
    // Set date format to set It as screenshot file name.
    dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
    // Create folder under project with name "screenshots" provided to destDir.
    new File(destDir).mkdirs();
    // Set file name using current date time.
    String destFile = dateFormat.format(new Date()) + ".png";

    try {
        FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:alimama    文件:SeleniumUtil.java   
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String capture(WebDriver driver, String url, String filePath) {
    if (driver == null) {
        return null;
    }
    if (!url.startsWith("http:") && !url.startsWith("https:")) {
        return null;
    }
    if (StringUtils.isBlank(filePath)) {
        return null;
    }
    try {
        driver.get(url);
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        File file = new File(filePath);
        FileUtils.copyFile(screenshot, file);
        logger.info("capture success!");
    } catch (IOException e) {
        logger.error("browser capture is error!", e);
        filePath = null;
        throw new RuntimeException(e);
    }
    return filePath;
}
项目:alimama    文件:SeleniumUtil.java   
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String capture(WebDriver driver, String url, String filePath) {
    if (driver == null) {
        return null;
    }
    if (!url.startsWith("http:") && !url.startsWith("https:")) {
        return null;
    }
    if (StringUtils.isBlank(filePath)) {
        return null;
    }
    try {
        driver.get(url);
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        File file = new File(filePath);
        FileUtils.copyFile(screenshot, file);
        logger.info("capture success!");
    } catch (IOException e) {
        logger.error("browser capture is error!", e);
        filePath = null;
        throw new RuntimeException(e);
    }
    return filePath;
}
项目:alimama    文件:SeleniumUtil.java   
/**
 * 鎴浘
 * 
 * @param driver
 * @param url
 * @param filePath
 * @return
 */
public static String captureDataoke(WebDriver driver, String url, String filePath) {
    if (driver == null) {
        return null;
    }
    if (!url.startsWith("http:") && !url.startsWith("https:")) {
        return null;
    }
    if (StringUtils.isBlank(filePath)) {
        return null;
    }
    try {
        driver.get(url);
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        File file = new File(filePath);
        FileUtils.copyFile(screenshot, file);
        logger.info("capture success!");
    } catch (IOException e) {
        logger.error("browser capture is error!", e);
        filePath = null;
        throw new RuntimeException(e);
    }
    return filePath;
}
项目:sentinela    文件:PrintsScreen.java   
public static File printWebElement(WebElement element, WebDriver driver) throws IOException {
    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    Point p = element.getLocation();
    int width = element.getSize().getWidth();
    int height = element.getSize().getHeight();
    BufferedImage img = null;
    BufferedImage dest = null;
    img = ImageIO.read(scrFile);
    if (element.isDisplayed()) {
        dest = img.getSubimage(p.getX(), p.getY(), width, height);
    } else {
        dest = img.getSubimage(0, 0, 1, 1);
    }
    ImageIO.write(dest, ManipulateFiles.getListString("imgExtension"), scrFile);
    return scrFile;
}
项目:jwebrobot    文件:Screenshooter.java   
public void takeScreenshot(ScenarioExecutionContext scenarioContext, Action action){
    WebDriver driver = scenarioContext.getDriver();

    if(driver instanceof TakesScreenshot){
        ScenarioExecutionContext scenarioRootContext = scenarioContext.getRoot();
        BufferedImage screenshot = new AShot()
         .shootingStrategy(getShootingStrategy(scenarioRootContext))
         .takeScreenshot(driver).getImage();
        String format = getScreenshotFormat(scenarioRootContext);
        String targetFileName = getFileName(scenarioRootContext, action, format);
        try {
            ImageIO.write(screenshot, format, new File(targetFileName));
        } catch (IOException e) {
            throw new NonReadableFileException(targetFileName, e);
        }
    }
}
项目:hugegherkin    文件:SeleniumHelperImpl.java   
/**
 * Gets screen shot.
 *
 * @param driver   the driver
 * @param filename the filename
 *
 * @return the screen shot
 *
 * @throws IOException the iO exception
 */
public File getScreenShot(WebDriver driver, String filename) throws IOException {
    File imageFile = null;
    try {
        createScreenShotDir();

        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        String path = pathToScreenshot + relativeScreenshotPath + filename + scrFile.getName();
        imageFile = new File(path);
        FileUtils.copyFile(scrFile, imageFile);
        logger.debug("We are taking screenshots!");
    } catch (Exception ex) {
        // Any exception in Screen shot should be eaten here. It should not hamper selenium tests.
        logger.debug("Something went wrong getting a screenshots");
    }
    return imageFile;
}
项目:seleniumMvnScreenshot    文件:FailTestScreenshotListener.java   
@Override
public void onTestFailure(ITestResult tr) {
    super.onTestFailure(tr);

    WebDriver webDriver = findWebDriverByReflection(tr.getInstance()    );
    if (webDriver == null) {
        System.err.println(String.format("The test class '%s' does not have any field/method of type 'org.openqa.selenium.WebDriver'. " +
                "ScreenshotTestListener can not continue.", tr.getInstance().getClass().getName()));
        return;
    }

    File f = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
    try {
        final long timestamp = new Date().getTime();
        Path screenshotPath = Paths.get(currentDir, "target", "screenshot_" + tr.getMethod().getMethodName() + "_" + timestamp + ".png");
        System.out.println("copying " + screenshotPath);
        Files.copy(f.toPath(), screenshotPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.err.println("error during the screenshot copy file operation:" + e.getMessage());
    }

}
项目:kc-rice    文件:WebDriverScreenshotHelper.java   
/**
 * Screenshots will be saved using either the value of (#REMOTE_DRIVER_SCREENSHOT_FILENAME or if none, testName.testNameMethod)
 * appended with a date time stamp and the png file extension.
 *
 * @see WebDriverUtils#getDateTimeStampFormatted
 *
 * @param driver to use, if not of type TakesScreenshot no screenshot will be taken
 * @param testName to save test as, unless #REMOTE_DRIVER_SCREENSHOT_FILENAME is set
 * @param testMethodName to save test as, unless #REMOTE_DRIVER_SCREENSHOT_FILENAME is set
 * @throws IOException
 */
public void screenshot(WebDriver driver, String testName, String testMethodName, String screenName) throws IOException {
    if (driver instanceof TakesScreenshot) {

        if (!"".equals(screenName)) {
            screenName = "-" + screenName;
        }

        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        // It would be nice to make the screenshot file name much more configurable.
        String screenshotFileName = WebDriverUtils.getDateTimeStampFormatted() + "-"
                + System.getProperty(REMOTE_DRIVER_SCREENSHOT_FILENAME, testName + "." + testMethodName)
                + screenName + ".png";
        FileUtils.copyFile(scrFile, new File(System.getProperty(REMOTE_DRIVER_SCREENSHOT_DIR, ".")
                + File.separator, screenshotFileName));
        String archiveUrl = System.getProperty(REMOTE_DRIVER_SCREENSHOT_ARCHIVE_URL, "");
        WebDriverUtils.jGrowl(driver, "Screenshot", false, archiveUrl + screenshotFileName);
    }
}
项目:seleniumtestsframework    文件:ScreenshotUtil.java   
public static String captureEntirePageScreenshotToString(final WebDriver driver, final String arg0) {
    if (driver == null) {
        return "";
    }

    try {

        // Don't capture snapshot for htmlunit
        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) {
            return null;
        }

        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.Android.getBrowserType())) {
            return null;
        }

        TakesScreenshot screenShot = (TakesScreenshot) driver;
        return screenShot.getScreenshotAs(OutputType.BASE64);
    } catch (Exception ex) {

        // Ignore all exceptions
        ex.printStackTrace();
    }

    return "";
}
项目:webcat-testing-platform    文件:NullPageObject.java   
@Override
protected void takeScreenshotImpl(String methodName) {
    try {
        final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        final IContext context = Context.getInstance();
        context.addScreenshot(screenshot);
    }
    catch(UnreachableBrowserException ex) {
        logger.log(Level.WARN, "Could not reach browser to take screenshot");
    }
    catch(WebDriverException webDriverEx) {
        if(webDriverEx.getMessage().contains("Session not found")) {
            logger.log(Level.WARN, "Could not reach browser to take screenshot");
        } else {
            throw webDriverEx;
        }
    }
}
项目:FuncaoWeb    文件:Nucleo.java   
/**
 * Tira uma foto da p�gina
 * 
 * @param path
 *            - Retorna o local que a imagem foi gravada.
 * @author Rog�rio Figueiredo.
 */

public String captureScreen(String path) {
    path = path + "\\";
    try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File source = ((TakesScreenshot) augmentedDriver)
                .getScreenshotAs(OutputType.FILE);
        path = path + source.getName();
        FileUtils.copyFile(source, new File(path));
    } catch (IOException e) {
        path = "Failed to capture screenshot: " + e.getMessage();
    }

    System.out.println("Local que foi gravado a imagem: " + path);
    return path;
}
项目:edx-app-android    文件:NativeAppDriver.java   
/**
 * Captures the screenshot
 */
public void captureScreenshot() {
    String outputPath = PropertyLoader.loadProperty("output.path").get();

    String screenShotPath = outputPath + "/ScreenShots/";
    String fileName = generateFileName() + ".jpg";
    // Take the screenshot
    File scrFile = ((TakesScreenshot) (this.appiumDriver))
            .getScreenshotAs(OutputType.FILE);
    try {
        FileUtils.copyFile(scrFile, new File(screenShotPath + fileName));
        Reporter.log("<br> Module name: " + getCurrentTestClassName()
                + "<br>");
        Reporter.log(" Refer to <a href=\"ScreenShots/" + fileName
                + "\" target = \"_blank\"><img src=\"ScreenShots/"
                + fileName + "\" width=\"50\" height=\"50\"></a><br>");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:AppiumTestDistribution    文件:Hooks.java   
@After
public void afterClass(Scenario scenario) throws InterruptedException, IOException {
    if (scenario.isFailed()) {
        try {
            byte[] screenshot =
                    ((TakesScreenshot) AppiumDriverManager.getDriver())
                            .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        } catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } catch (ClassCastException cce) {
            cce.printStackTrace();
        }
        System.out.println("Inside After" + Thread.currentThread().getId());
    }
    AppiumDriverManager.getDriver().quit();

}
项目:kspl-selenium-helper    文件:MiscellaneousFunctions.java   
/**
 * This function is used to capture screenshot and store it in directory
 * @param driver -Pass your WebDriver instance.
 * @param screenshotdir - Pass your screenshot directory
 * @return - Returns location where screenshot is stored.
 * @throws IOException -Exception is thrown during communcation errors.
    */
public static String captureScreenshot(WebDriver driver,
        String screenshotdir) throws IOException {
    String randomUUID = UUID.randomUUID().toString();
    String storeFileName = screenshotdir + File.separator
            + getFileNameFromURL(driver.getCurrentUrl()) + "_"
            + randomUUID + ".png";
    String[] screenshotdirsplit = screenshotdir.split(File.separator);
    String fileName = screenshotdirsplit[screenshotdirsplit.length - 1] + File.separator
            + getFileNameFromURL(driver.getCurrentUrl()) + "_"
            + randomUUID + ".png";
    File scrFile = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(storeFileName));
    return fileName;
}
项目:netarchivesuite-svngit-migration    文件:SeleniumTest.java   
@AfterMethod
/**
 * Takes care of failure situations. This includes: <ol>
 * <li> Generate a a screen dump of the page failing the test.
 * <ol>
 * 
 * This method is called by TestNG.
 * 
 * @param result The result which TestNG will inject
 */
public void onFailure(ITestResult result) { 
    if (!result.isSuccess()) { 
        log.info("Test failure, dumping screenshot as " + "target/failurescreendumps/" + 
                result.getMethod() + ".png");
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile, new File("failurescreendumps/" + result.getMethod() + ".png"));
        } catch (IOException e) {
            log.error("Failed to save screendump on error");
        }
    }
}
项目:VirtusaSeleniumWebdriverRuntime    文件:ScreenshotListenerVir.java   
/**
 * On test failure.
 * 
 * result the result
 * 
 * @param result
 *            the result
 * @see org.testng.ITestListener#onTestFailure(org.testng.ITestResult)
 */
@Override
public final void onTestFailure(final ITestResult result) {
    Reporter.setCurrentTestResult(result);

    try {

        if (outputDirectory.mkdirs()) {
            String fileloc = getProperties();
            File scrFile =
                    ((TakesScreenshot) driver)
                            .getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File(fileloc + ".png"));
            Reporter.log("<a href='" + fileloc + ".png'>screenshot</a>");
        } else {
            System.err.println("Creation of directory failed "
                    + outputDirectory.getAbsolutePath());
        }
    } catch (Exception e) {
        e.printStackTrace();
        Reporter.log("Couldn't create screenshot");
        Reporter.log(e.getMessage());
    }

    Reporter.setCurrentTestResult(null);
}
项目:carbon-platform-integration-utils    文件:UIManagementListener.java   
/**
 * Capture the current web browser screen and save it.
 *
 * @param fullTestName - Full name of the test case.
 */
private void doScreenCapture(String fullTestName) {
    WebDriver webDriver = BrowserManager.driver;
    try {
        log.info("Screen capturing Start : " + fullTestName);
        // Retrieve report location of the Test Framework
        String reportLocation = FrameworkPathUtil.getReportLocation();
        long currentTime = System.currentTimeMillis();
        DateFormat dateFormat = new SimpleDateFormat(ExtensionCommonConstants.DATE_FORMAT_YY_MM_DD_HH_MIN_SS);
        Calendar cal = Calendar.getInstance();
        //Image path looks like :
        // [reportlocation]/capturedscreens/failedtests/[fullTestName]_[Date]_[Current time in milliseconds].png
        String imagePath =
                reportLocation + File.separator + ExtensionCommonConstants.SCREEN_SHOT_LOCATION + File.separator +
                        fullTestName + "_" + dateFormat.format(cal.getTime()) + "_" + currentTime +
                        ExtensionCommonConstants.SCREEN_SHOT_EXTENSION;
        File scrFile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(imagePath));
        log.info("Screen capturing End : " + fullTestName);
    } catch (IOException e) {
        //  Even having problems in screen shot  generation, test need to be continued hence not throwing any exceptions.
        log.warn("Error in screen capturing  for test failure in " + fullTestName, e);
    }
}
项目:hsac-fitnesse-fixtures    文件:SeleniumHelper.java   
/**
 * Takes screenshot of current page (as .png).
 * @param baseName name for file created (without extension),
 *                 if a file already exists with the supplied name an
 *                 '_index' will be added.
 * @return absolute path of file created.
 */
public String takeScreenshot(String baseName) {
    String result = null;

    WebDriver d = driver();

    if (!(d instanceof TakesScreenshot)) {
        d = new Augmenter().augment(d);
    }
    if (d instanceof TakesScreenshot) {
        TakesScreenshot ts = (TakesScreenshot) d;
        byte[] png = ts.getScreenshotAs(OutputType.BYTES);
        result = writeScreenshot(baseName, png);
    }
    return result;
}
项目:testdroid-samples    文件:BaseTest.java   
protected File takeScreenshot(String screenshotName) {
    String fullFileName = System.getProperty("user.dir") + "/screenshots/" + screenshotName + ".png";
    logger.debug("Taking screenshot...");
    File scrFile = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);

    try {
        File testScreenshot = new File(fullFileName);
        FileUtils.copyFile(scrFile, testScreenshot);
        logger.debug("Screenshot stored to " + testScreenshot.getAbsolutePath());

        return testScreenshot;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目:JGiven    文件:Html5AppTest.java   
@Test
@Issue( "#274" )
@DataProvider( {
    "true",
    "false" } )
public void showing_thumbnails_can_be_configured( boolean thumbOption ) throws IOException {
    String screenshot = ( (TakesScreenshot) webDriver ).getScreenshotAs( OutputType.BASE64 );

    given().a_report_model()
        .and().step_$_of_scenario_$_has_an_image_attachment_$( 1, 1, screenshot );
    jsonReports
        .and().the_report_exist_as_JSON_file();
    whenReport.when().showing_thumbnails_is_set_to( thumbOption )
        .and().the_HTML_Report_Generator_is_executed();
    when().the_page_of_scenario_$_is_opened( 1 );
    if( thumbOption ) {
        then().an_element_with_a_$_class_exists( "jgiven-html-thumbnail" )
            .and().the_image_is_loaded();
    } else {
        then().$_attachment_icons_exist( 1 );
    }
}