List of usage examples for org.openqa.selenium TakesScreenshot getScreenshotAs
<X> X getScreenshotAs(OutputType<X> target) throws WebDriverException;
From source file:Util.java
License:Apache License
/** * // Takes a screen shot if the driver's capabilities include Screen Shots * @param driver The Web Driver instance * @param outputType Either FILE or Base64 * @param folder The folder for images * @param filename The base file name (sans time stamp) * @return Error string starting with ERROR: if failed to create file or the file name that was created *//* w w w. ja va 2 s.c om*/ public static String takeScreenImage(WebDriver driver, String folder, String fileName) { String result = ""; WebDriver theDriver = Driver.getDriver(); if (!(theDriver instanceof WebDriver)) { return "ERROR: No Web Driver found at this step!"; } if (!((HasCapabilities) theDriver).getCapabilities().is(CapabilityType.TAKES_SCREENSHOT)) { return "ERROR: Driver " + Util.sq(theDriver.toString()) + " has no TAKES_SCREENSHOT capabilities. Screen shot not taken"; } String imagesFolder = (isBlank(folder)) ? DDTTestRunner.getReporter().sessionImagesFolderName() : folder; try { File testTempDir = new File(DDTSettings.asValidOSPath(imagesFolder, true)); if (testTempDir.exists()) { if (!testTempDir.isDirectory()) { return "ERROR: Image path exists but is not a directory"; } } else { testTempDir.mkdirs(); } } catch (Exception e) { return "ERROR: File operation (mkdir) failed. " + e.getCause(); } String actualFileName = fileName + " - " + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".png"; // create screenshot using a casted driver TakesScreenshot snapper = (TakesScreenshot) theDriver; if (DDTSettings.Settings().isLocal()) { File tempImageFile = snapper.getScreenshotAs(OutputType.FILE); if (tempImageFile.length() < (1L)) { return "ERROR: Failed to take screen shot on remote driver"; } File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); // testTempImage // move screenshot to our local store try { FileUtils.moveFile(tempImageFile, tmpFile); } catch (Exception e) { return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()) + " " + e.getCause().toString(); } if (tmpFile.length() < 1L) { return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()); } result = tmpFile.getAbsolutePath(); } else { // Create Base64 screen shot file on the remote driver and store it locally String tempImageFile = snapper.getScreenshotAs(OutputType.BASE64); if (tempImageFile.length() < (1L)) { return "ERROR: Failed to take screen shot on remote driver"; } Base64 decoder = new Base64(); byte[] imgBytes = (byte[]) decoder.decode(tempImageFile); File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); FileOutputStream osf = null; try { osf = new FileOutputStream(tmpFile); osf.write(imgBytes); osf.flush(); } catch (Exception e) { return "ERROR: Failed to create File Output Stream " + e.getCause(); } if (tmpFile.length() < 1L) { return "ERROR: File created from File Output Stream is empty!"; } result = tmpFile.getAbsolutePath(); } return result; }
From source file:cc.gospy.example.basic.SeleniumDemo.java
License:Apache License
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())/*from w w w . j a v a 2 s. c o m*/ .build().addTask("phantomjs://http://www.zhihu.com").start(); }
From source file:ch.vorburger.webdriver.reporting.LoggingWebDriverEventListener.java
License:Apache License
/** * This method will take snap shots of screens and save them. * * @param driver WebDriver// w w w .j a v a2 s . c o m * @param element WebElement * @param log message from the action */ protected void logAndTakeSnapShot(WebDriver driver, WebElement element, String log) { addStyleBeforeSnapShot(element, driver); if (driver instanceof EventFiringWebDriver) { EventFiringWebDriver eventFiringWebDriver = (EventFiringWebDriver) driver; driver = eventFiringWebDriver.getWrappedDriver(); } if (driver instanceof TakesScreenshot) { TakesScreenshot takesScreenshotWebDriver = (TakesScreenshot) driver; File srcFile = takesScreenshotWebDriver.getScreenshotAs(OutputType.FILE); log(element, log, srcFile); removeStyleafterSnapShot(element, driver); } else { log(element, log, null); } }
From source file:com.autocognite.appium.lib.base.AbstractAppiumUiDriver.java
License:Apache License
@Override public File takeScreenshot() throws Exception { TakesScreenshot augDriver = getScreenshotAugmentedDriver(); File srcFile = augDriver.getScreenshotAs(OutputType.FILE); return FileSystemBatteries.moveFiletoDir(srcFile, this.getRunConfig().get(Configurator.TEMP_SCREENSHOTS_DIR)); }
From source file:com.elastica.driver.ScreenshotUtil.java
License:Apache License
public static String captureEntirePageScreenshotToString(final WebDriver driver, final String arg0) { if (driver == null) { return ""; }/* w ww . j av a2 s .com*/ try { // Don't capture snapshot for htmlunit if (WebUIDriver.getWebUXDriver().getBrowser().equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) { return null; } // Opera has bug after upgrade selenium // 2.33.0,https://code.google.com/p/selenium/issues/detail?id=847 if (WebUIDriver.getWebUXDriver().getBrowser().equalsIgnoreCase(BrowserType.Opera.getBrowserType())) { return null; } TakesScreenshot screenShot = (TakesScreenshot) driver; return screenShot.getScreenshotAs(OutputType.BASE64); } catch (Exception ex) { // Ignore all exceptions ex.printStackTrace(); } return ""; }
From source file:com.ggasoftware.uitest.utils.ScreenShotMaker.java
License:Open Source License
/** * create screenshot on remote machine/*w w w .ja va2 s .co m*/ * * @param id - name output png file * @return full path */ public static String takeScreenshotRemote(String id) { String sId = id; String base64Screenshot; if (hasTake) { if (isDirectoryCorrect()) { String name = String.format("%s.png", DateUtil.now(new SimpleDateFormat("HH_mm_ss-sss").toPattern())); try { TakesScreenshot tsDriver; tsDriver = (TakesScreenshot) WebDriverWrapper.getDriver(); base64Screenshot = tsDriver.getScreenshotAs(OutputType.BASE64); byte[] decodedScreenshot = Base64.decodeBase64(base64Screenshot.getBytes()); File file = new File(ScreenShotMaker.path + name); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(decodedScreenshot); } if (TestBaseWebDriver.allure) { saveScreenshot(decodedScreenshot); } if (TestBaseWebDriver.reportportal) { ReporterNGExt.log4j(new ReportPortalMessage(file, id)); } } catch (WebDriverException | IOException e) { sId += String.format(" [%s when making screenshot(webdriver: %s)]", e.toString(), WebDriverWrapper.getDriver()); ReporterNGExt.log4jError(String.format("%s when making screenshot(webdriver: %s; file: %s%s) ", e.toString(), WebDriverWrapper.getDriver(), ScreenShotMaker.path, name)); } return dir + name + "|" + sId; } ReporterNGExt.log4jError(String.format("Incorrect directory screenshot directory: %s", path)); return String.format("Incorrect directory screenshot directory: %s", path); } else { return id; } }
From source file:com.google.caja.plugin.WebDriverHandle.java
License:Apache License
public void captureResults(String name) { if (driver == null) { return;//from ww w . ja v a 2 s . c o m } String dir = TestFlag.CAPTURE_TO.getString(""); if ("".equals(dir)) { return; } if (!dir.endsWith("/")) { dir = dir + "/"; } mkdirs(dir); // Try to capture the final html try { String source = driver.getPageSource(); if (source != null) { saveToFile(dir + name + ".capture.html", source); } } catch (WebDriverException e) { Echo.echo("capture html failed: " + e); } // Try to capture a screenshot if (driver instanceof TakesScreenshot) { TakesScreenshot ss = (TakesScreenshot) driver; try { byte[] bytes = ss.getScreenshotAs(OutputType.BYTES); saveToFile(dir + name + ".capture.png", bytes); } catch (WebDriverException e) { Echo.echo("capture screenshot failed: " + e); } } // Try to capture logs try { Logs logs = driver.manage().logs(); if (logs != null) { if (logs.getAvailableLogTypes().contains(LogType.BROWSER)) { LogEntries entries = logs.get(LogType.BROWSER); if (entries != null) { StringBuilder sb = new StringBuilder(); for (LogEntry e : entries) { sb.append(e.toString() + "\n"); } saveToFile(dir + name + ".capture.log", sb.toString()); } } } } catch (WebDriverException e) { Echo.echo("capture logs failed: " + e); } }
From source file:com.googlecode.fightinglayoutbugs.ScreenshotCache.java
License:Apache License
private Screenshot takeScreenshot(TakesScreenshot driver) { byte[] bytes = driver.getScreenshotAs(OutputType.BYTES); if (bytes == null) { throw new RuntimeException( driver.getClass().getName() + ".getScreenshotAs(OutputType.BYTES) returned null."); }/*from ww w .j a v a2 s . com*/ if (bytes.length < 8) { throw new RuntimeException( driver.getClass().getName() + ".getScreenshotAs(OutputType.BYTES) did not return a PNG image."); } else { // Workaround for http://code.google.com/p/selenium/issues/detail?id=1686 ... if (!asList(bytes).subList(0, 8).equals(PNG_SIGNATURE)) { bytes = Base64.decodeBase64(bytes); } if (!asList(bytes).subList(0, 8).equals(PNG_SIGNATURE)) { throw new RuntimeException(driver.getClass().getName() + ".getScreenshotAs(OutputType.BYTES) did not return a PNG image."); } } int[][] pixels = ImageHelper.pngToPixels(bytes); return new Screenshot(pixels); }
From source file:com.huangyunkun.jviff.JViff.java
License:Apache License
public void run() throws IOException { Config config = prepareEnv();//from ww w .j av a2 s. c om TakesScreenshot takesScreenshot = prepareWebDriver(config); int stepId; int hostId = 0; List<StepResult> stepResults = Lists.newArrayList(); for (Step step : stepContainer.getSteps()) { stepResults.add(new StepResult(step)); } for (String host : config.getEnvHosts()) { stepContainer.setHost(host); stepId = 0; for (int i = 0; i < stepContainer.getSteps().size(); i++) { Step step = stepContainer.getSteps().get(i); stepContainer.runStep(driver, step); if (step.getRecord()) { File screenShot = takesScreenshot.getScreenshotAs(OutputType.FILE); String fileName = String.format("%d-%d.png", hostId, stepId); stepResults.get(i).addImage(fileName); Files.copy(screenShot, new File(outputDir, fileName)); stepId++; } } hostId++; } for (int i = 0; i < stepResults.size(); i++) { StepResult stepResult = stepResults.get(i); if (stepResult.getStep().getRecord()) { File one = new File(outputDir, stepResult.getFirstImage()); File two = new File(outputDir, stepResult.getSecondImage()); comparator.compare(one, two, stepResult); if (!stepResult.getSuccess()) { diffGenerator.report(one, two, outputDir.getAbsolutePath(), stepResult); logger.error("Image is diff. " + stepContainer.getSteps().get(i)); } } } resultReporter.report(stepResults, outputDir); driver.quit(); }
From source file:com.ibm.watson.movieapp.dialog.fvt.config.TestWatcherRule.java
License:Open Source License
@Override protected void failed(Throwable e, Description description) { TakesScreenshot takesScreenshot = (TakesScreenshot) browser; File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE); File destFile = getDestinationFile(description.getMethodName()); try {/*from w ww .jav a2 s .com*/ FileUtils.copyFile(scrFile, destFile); } catch (IOException ioe) { throw new RuntimeException(ioe); } }