org.openqa.selenium.OutputType Java Examples

The following examples show how to use org.openqa.selenium.OutputType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SeleniumUtils.java    From NetDiscovery with Apache License 2.0 6 votes vote down vote up
/**
 * 截取某个区域的截图
 * @param driver
 * @param x
 * @param y
 * @param width
 * @param height
 * @param pathName
 */
public static void taskScreenShot(WebDriver driver,int x,int y,int width,int height,String pathName) {

    //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
    File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    //利用IOUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

    try {
        //矩形图像对象
        Rectangle rect = new Rectangle(width, height);
        BufferedImage img = ImageIO.read(srcFile);
        BufferedImage dest = img.getSubimage(x, y, rect.width, rect.height);
        ImageIO.write(dest, "png", srcFile);
        IOUtils.copyFile(srcFile, new File(pathName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: SeleniumDriver.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: BaseWebDrive.java    From LuckyFrameClient with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * �����Խ�����н�ͼ
 * @param driver ����
 * @param imgname ͼƬ����
 */
public static void webScreenShot(WebDriver driver, String imgname) {
	String relativelyPath = System.getProperty("user.dir");
	String pngpath=relativelyPath +File.separator+ "log"+File.separator+"ScreenShot" +File.separator+ imgname + ".png";

	// ��Զ��ϵͳ���н�ͼ
	driver = new Augmenter().augment(driver);
	File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	try {
		FileUtils.copyFile(scrFile, new File(pngpath));
	} catch (IOException e) {
		LogUtil.APP.error("��ͼ����ʧ�ܣ��׳��쳣��鿴��־...", e);
	}
	scrFile.deleteOnExit();
	LogUtil.APP
			.info("�ѶԵ�ǰ������н�ͼ��������ͨ������ִ�н������־��ϸ�鿴��Ҳ����ǰ���ͻ����ϲ鿴...��{}��",pngpath);
}
 
Example #4
Source File: Downloader.java    From twse-captcha-solver-dl4j with MIT License 6 votes vote down vote up
private void downloadCaptcha(WebElement element) {
	// take all webpage as screenshot
	File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	try {
		// read the full screenshot
		BufferedImage fimg = ImageIO.read(screenshot);
		// get element location
		org.openqa.selenium.Point p = element.getLocation();
		// find element size
		org.openqa.selenium.Dimension size = element.getSize();
		// corp the captcha image
		BufferedImage croppedImage = fimg.getSubimage(p.getX(), p.getY(), size.getWidth(),
				size.getHeight());
		// save the capthca image
		File f = new File(this.saveDir + File.separator + randomImgName());
		ImageIO.write(croppedImage, "PNG", f);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		// delete tmp file
		screenshot.delete();
	}
}
 
Example #5
Source File: Edition088_Debugging_Aids.java    From appiumpro with Apache License 2.0 6 votes vote down vote up
@Override
protected void failed(Throwable e, Description desc) {
    // print appium logs
    LogEntries entries = driver.manage().logs().get("server");
    System.out.println("======== APPIUM SERVER LOGS ========");
    for (LogEntry entry : entries) {
        System.out.println(new Date(entry.getTimestamp()) + " " + entry.getMessage());
    }
    System.out.println("================");

    // print source
    System.out.println("======== APP SOURCE ========");
    System.out.println(driver.getPageSource());
    System.out.println("================");

    // save screenshot
    String testName = desc.getMethodName().replaceAll("[^a-zA-Z0-9-_\\.]", "_");
    File screenData = driver.getScreenshotAs(OutputType.FILE);
    try {
        File screenFile = new File(SCREEN_DIR + "/" + testName + ".png");
        FileUtils.copyFile(screenData, screenFile);
        System.out.println("======== SCREENSHOT ========");
        System.out.println(screenFile.getAbsolutePath());
        System.out.println("================");
    } catch (IOException ign) {}
}
 
Example #6
Source File: Edition082_Mjpeg_Video_Streaming_iOS.java    From appiumpro with Apache License 2.0 6 votes vote down vote up
@Test
public void timeScreenshotsWithMjpegScreenshotBehavior() throws IOException, URISyntaxException, InterruptedException, ExecutionException, TimeoutException {

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("platformName", "iOS");
    caps.setCapability("platformVersion", "12.4");
    caps.setCapability("deviceName", "iPhone Xs");
    caps.setCapability("automationName", "XCUITest");
    caps.setCapability("app", IOS_APP);

    driver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);

    driver.startRecordingScreen(); // this is unnecessary for this test run, but included here to make this test identical to the next test

    long startTime = System.nanoTime();
    for (int i = 0; i < 100; i++) {
        driver.getScreenshotAs(OutputType.FILE);
    }
    long endTime = System.nanoTime();

    long msElapsed = (endTime - startTime) / 1000000;
    System.out.println("100 screenshots using mjpeg: " + msElapsed + "ms. On average " + msElapsed/100 + "ms per screenshot");
    // about 436ms per screenshot on my machine
}
 
Example #7
Source File: MiscellaneousFunctions.java    From kspl-selenium-helper with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: FluentLeniumAdapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] captureScreen() {
    if (fluent == null) {
        return null;
    }
    WebDriver driver = fluent.getDriver();
    if (driver == null) {
        return null;
    }
    if (!(driver instanceof TakesScreenshot)) {
        return null;
    }
    try {
        return ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BYTES);
    } catch (NoSuchSessionException e) {
        // just do nothing if WebDriver instance is in invalid state
        return null;
    }
}
 
Example #9
Source File: WebDriverScreenshotHelper.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #10
Source File: ScreenshotUtils.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Produce a screenshot from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object; may be 'null'
 * @return screenshot artifact; if capture fails, an empty byte array is returned
 */
public static byte[] getArtifact(
                final Optional<WebDriver> optDriver, final Throwable reason, final Logger logger) { //NOSONAR
    
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        } catch (WebDriverException e) {
            if (e.getCause() instanceof ClassCastException) {
                return proxyArtifact();
            } else if (logger != null) {
                logger.warn("The driver is capable of taking a screenshot, but it failed.", e);
            }
        }
    }
    return new byte[0];
}
 
Example #11
Source File: NativeAppDriver.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #12
Source File: BaseTest.java    From test-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: WebDriverWebController.java    From stevia with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void takeScreenShot() throws IOException {

	File scrFile = null;
	try {
		scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	} catch (Exception e) {
		WEBDRIVER_LOG.error("Failed to generate screenshot, problem with driver: {} ", e.getMessage());
	}

	if (scrFile != null) {
		File file = createScreenshotFile();
		FileUtils.copyFile(scrFile, file);

		reportLogScreenshot(file);
	}
}
 
Example #14
Source File: ScreenshotUtil.java    From seleniumtestsframework with Apache License 2.0 6 votes vote down vote up
public static String captureEntirePageScreenshotToString(final WebDriver driver) {
    if (driver == null) {
        return "";
    }

    try {
        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 "";
}
 
Example #15
Source File: VisualAssertion.java    From neodymium-library with MIT License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #16
Source File: CucumberRunner.java    From testng-cucumber with MIT License 5 votes vote down vote up
@AfterMethod(alwaysRun = true)
public void tearDownr(ITestResult result) throws IOException {
	if (result.isSuccess()) {
		File imageFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
		String failureImageFileName = result.getMethod().getMethodName()
				+ new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime()) + ".png";
		File failureImageFile = new File(System.getProperty("user.dir") + "//screenshots//" + failureImageFileName);
		failureImageFile.getParentFile().mkdir();
		failureImageFile.createNewFile();
		Files.copy(imageFile, failureImageFile);
	}

}
 
Example #17
Source File: QAFExtendedWebDriver.java    From qaf with MIT License 5 votes vote down vote up
public <T> T extractScreenShot(WebDriverException e, OutputType<T> target) {
	if (e.getCause() instanceof ScreenshotException) {
		String base64Str = ((ScreenshotException) e.getCause()).getBase64EncodedScreenshot();
		return target.convertFromBase64Png(base64Str);
	}
	return null;
}
 
Example #18
Source File: SeleniumProvider.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public void takeScreenShot() {
    try {
        log.info("Taking screenshot");
        browserScreenshots.put(new Date(), ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));
    } catch (Exception ex) {
        log.warn("Cannot take screenshot: {}", ex.getMessage());
    }
}
 
Example #19
Source File: TestdroidImageRecognition.java    From test-samples with Apache License 2.0 5 votes vote down vote up
protected void takeScreenshot(String screenshotName) throws IOException {
    try {
        ImageRecognition.takeScreenshot(screenshotName, screenshotsFolder, platform);
    } catch (Exception e) {
        File scrFile = driver.getScreenshotAs(OutputType.FILE);
        String screenshotFile = screenshotsFolder + screenshotName + ".png";
        String screenShotFilePath = System.getProperty("user.dir") + "/" + screenshotFile;
        File testScreenshot = new File(screenShotFilePath);
        FileUtils.copyFile(scrFile, testScreenshot);
        logger.info("Screenshot stored to {}", testScreenshot.getAbsolutePath());
        return;
    }
}
 
Example #20
Source File: HtmlExporter2BYTES.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片 byte 数组
 */
@Override
public byte[] convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.BYTES);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #21
Source File: IntegrationTestHelper.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void takeScreenshot(WebDriver browser, String screenshotName) {
    if (browser instanceof TakesScreenshot) {
        String testCaseClass  = calledByClass();
        String testCaseMethod = calledByMethod();

        File tempfile = ((TakesScreenshot) browser).getScreenshotAs(OutputType.FILE);
        File dumpfile = new File(screenShotParentDir.getAbsolutePath() + File.separator  + "scrshot-" + runNo + "-" + testCaseClass + "-" + testCaseMethod + "-" + screenshotName + ".png");
        tempfile.renameTo(dumpfile);
        System.err.println("Screen shot dumped to: " + dumpfile.getAbsolutePath());
    } else {
        System.err.println("Browser does not support screen shots.");
    }
}
 
Example #22
Source File: ScreenShot.java    From PatatiumAppUi with GNU General Public License v2.0 5 votes vote down vote up
private void takeScreenshot(String screenPath) {
	File scrFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	try {
		Files.copy(scrFile, new File(screenPath));
		log.error("错误截图:"+screenPath);
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}
 
Example #23
Source File: Screenshot.java    From webtau with Apache License 2.0 5 votes vote down vote up
private BufferedImage takeBufferedImage() {
    byte[] screenshotBytes = screenshotTaker.getScreenshotAs(OutputType.BYTES);
    try {
        return ImageIO.read(new ByteArrayInputStream(screenshotBytes));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: SeleniumUtils.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
public static void taskScreenShot(WebDriver driver,String pathName){

        //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //利用IOUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。

        try {
            IOUtils.copyFile(srcFile, new File(pathName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example #25
Source File: HtmlExporter2BASE64.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片 string 字符串
 */
@Override
public String convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.BASE64);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #26
Source File: PtlWebDriver.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
@Override
public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {
	X screenshot = super.getScreenshotAs(outputType);
	if (environmentConfig != null && environmentConfig.isDebug()) {
		exportDebugScreenshot(screenshot);
	}
	return screenshot;
}
 
Example #27
Source File: WebDriverBrowser.java    From webtester-core with Apache License 2.0 5 votes vote down vote up
@Override
public File takeScreenshot(final String targetFolder, final String fileNameWithoutSuffix) {
    return executeAction(new BrowserCallbackWithReturnValue<File>() {

        @Override
        public File execute(Browser browser) {

            if (!(getWebDriver() instanceof TakesScreenshot)) {
                return null;
            }

            TakesScreenshot takesScreenshot = ( TakesScreenshot ) getWebDriver();
            File tempScreenshot = takesScreenshot.getScreenshotAs(OutputType.FILE);

            String fileName = fileNameWithoutSuffix + ".png";
            File screenshot = new File(targetFolder, fileName);

            try {
                FileUtils.moveFile(tempScreenshot, screenshot);
            } catch (IOException e) {
                logger.warn("Exception while creating screenshot, returning null.", e);
                return null;
            }

            fireEvent(new TookScreenshotEvent(browser, screenshot));
            return screenshot;

        }

    });
}
 
Example #28
Source File: ScreenshotListener.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
private void writeScreenshotToFile(WebDriver driver, File screenshot) {
    try {
        FileOutputStream screenshotStream = new FileOutputStream(screenshot);
        screenshotStream.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
        screenshotStream.close();
    } catch (IOException unableToWriteScreenshot) {
        System.err.println("Unable to write " + screenshot.getAbsolutePath());
        unableToWriteScreenshot.printStackTrace();
    }
}
 
Example #29
Source File: TakesFullPageScreenshotTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetScreenshotAsFile() {
  driver.get(pages.simpleTestPage);
  tempFile = screenshooter.getFullPageScreenshotAs(OutputType.FILE);
  assertThat(tempFile.exists()).isTrue();
  assertThat(tempFile.length()).isGreaterThan(0);
}
 
Example #30
Source File: EventFiringWebDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
   if (driver instanceof TakesScreenshot) {
      dispatcher.beforeGetScreenshotAs(target);
      X screenshot = ((TakesScreenshot) driver).getScreenshotAs(target);
      dispatcher.afterGetScreenshotAs(target, screenshot);
      return screenshot;
   }

  throw new UnsupportedOperationException(
      "Underlying driver instance does not support taking screenshots");
}