类org.openqa.selenium.OutputType源码实例Demo

下面列出了怎么用org.openqa.selenium.OutputType的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * 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;
}
 
@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
}
 
源代码3 项目: appiumpro   文件: Edition088_Debugging_Aids.java
@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) {}
}
 
源代码4 项目: LuckyFrameClient   文件: BaseWebDrive.java
/**
 * �����Խ�����н�ͼ
 * @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);
}
 
源代码5 项目: NetDiscovery   文件: SeleniumUtils.java
/**
 * 截取某个区域的截图
 * @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();
    }
}
 
源代码6 项目: seleniumtestsframework   文件: ScreenshotUtil.java
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 "";
}
 
源代码7 项目: test-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;
}
 
源代码8 项目: 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);
    }
}
 
源代码9 项目: sahagin-java   文件: FluentLeniumAdapter.java
@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;
    }
}
 
源代码10 项目: twse-captcha-solver-dl4j   文件: Downloader.java
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();
	}
}
 
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;
}
 
源代码12 项目: Selenium-Foundation   文件: ScreenshotUtils.java
/**
 * 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];
}
 
源代码13 项目: 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();
	}
}
 
源代码14 项目: stevia   文件: WebDriverWebController.java
@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);
	}
}
 
源代码15 项目: neodymium-library   文件: 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;
    }
}
 
源代码16 项目: java-client   文件: ImagesComparisonTest.java
@Test
public void verifyOccurrencesLookup() {
    byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
    OccurrenceMatchingResult result = driver
            .findImageOccurrence(screenshot, screenshot, new OccurrenceMatchingOptions()
                    .withEnabledVisualization());
    assertThat(result.getVisualization().length, is(greaterThan(0)));
    assertNotNull(result.getRect());
}
 
源代码17 项目: webdsl   文件: Test.java
public static void takeScreenshot(WebDriver driver){
  	File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  	try {
  		File f = new File("screenshot-"+(screenshotCounter++)+"-"+new Date()+".png");
	FileUtils.copyFile(scrFile, f);
	org.webdsl.logging.Logger.info("screenshot saved "+f.getAbsolutePath());
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
源代码18 项目: vividus   文件: DelegatingWebElementTests.java
@SuppressWarnings("unchecked")
@Test
void testGetScreenshotAs()
{
    OutputType<String> target = Mockito.mock(OutputType.class);
    String output = "output";
    when(webElement.getScreenshotAs(target)).thenReturn(output);
    assertEquals(output, delegatingWebElement.getScreenshotAs(target));
}
 
源代码19 项目: vividus   文件: DelegatingWebDriverTests.java
@Test
void testGetScreenshotAs()
{
    WebDriver takesScreenshotDriver = Mockito.mock(WebDriver.class,
            withSettings().extraInterfaces(TakesScreenshot.class));
    File file = Mockito.mock(File.class);
    when(((TakesScreenshot) takesScreenshotDriver).getScreenshotAs(OutputType.FILE)).thenReturn(file);
    assertEquals(file, new DelegatingWebDriver(takesScreenshotDriver).getScreenshotAs(OutputType.FILE));
}
 
源代码20 项目: vividus   文件: DelegatingWebDriverTests.java
@Test
void testGetScreenshotAsUnsupportedOperationException()
{
    UnsupportedOperationException exception = assertThrows(UnsupportedOperationException.class,
        () -> delegatingWebDriver.getScreenshotAs(OutputType.FILE));
    assertEquals("Underlying driver instance does not support taking screenshots", exception.getMessage());
}
 
源代码21 项目: appiumpro   文件: Edition098_Visual_Testing_1.java
private void doVisualCheck(String checkName) throws Exception {
    String baselineFilename = VALIDATION_PATH + "/" + BASELINE + checkName + ".png";
    File baselineImg = new File(baselineFilename);

    // If no baseline image exists for this check, we should create a baseline image
    if (!baselineImg.exists()) {
        System.out.println(String.format("No baseline found for '%s' check; capturing baseline instead of checking", checkName));
        File newBaseline = driver.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(newBaseline, new File(baselineFilename));
        return;
    }

    // Otherwise, if we found a baseline, get the image similarity from Appium. In getting the similarity,
    // we also turn on visualization so we can see what went wrong if something did.
    SimilarityMatchingOptions opts = new SimilarityMatchingOptions();
    opts.withEnabledVisualization();
    SimilarityMatchingResult res = driver.getImagesSimilarity(baselineImg, driver.getScreenshotAs(OutputType.FILE), opts);

    // If the similarity is not high enough, consider the check to have failed
    if (res.getScore() < MATCH_THRESHOLD) {
        File failViz = new File(VALIDATION_PATH + "/FAIL_" + checkName + ".png");
        res.storeVisualization(failViz);
        throw new Exception(
            String.format("Visual check of '%s' failed; similarity match was only %f, and below the threshold of %f. Visualization written to %s.",
                checkName, res.getScore(), MATCH_THRESHOLD, failViz.getAbsolutePath()));
    }

    // Otherwise, it passed!
    System.out.println(String.format("Visual check of '%s' passed; similarity match was %f",
        checkName, res.getScore()));
}
 
@Test
public void testScreenshots() throws Exception {
    Thread.sleep(2000);
    String desktop = System.getenv("HOME") + "/Desktop";
    driver.rotate(ScreenOrientation.LANDSCAPE);
    File regularScreenshot = driver.getScreenshotAs(OutputType.FILE);
    driver.setSetting("screenshotOrientation", "landscapeRight");
    File adjustedScreenshot = driver.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(regularScreenshot, new File(desktop + "/screen1.png"));
    FileUtils.copyFile(adjustedScreenshot, new File(desktop + "/screen2.png"));
}
 
源代码23 项目: movieapp-dialog   文件: TestWatcherRule.java
@Override
protected void failed(Throwable e, Description description) {
    TakesScreenshot takesScreenshot = (TakesScreenshot) browser;

    File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
    File destFile = getDestinationFile(description.getMethodName());
    try {
        FileUtils.copyFile(scrFile, destFile);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
源代码24 项目: java-client   文件: ImagesComparisonTest.java
@Test
public void verifyOccurrencesSearch() {
    byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
    OccurrenceMatchingResult result = driver
            .findImageOccurrence(screenshot, screenshot, new OccurrenceMatchingOptions()
                    .withEnabledVisualization());
    assertThat(result.getVisualization().length, is(greaterThan(0)));
    assertNotNull(result.getRect());
}
 
源代码25 项目: test-samples   文件: AndroidSample.java
@Override
protected void failed(Throwable e, Description description) {
    String fullFileName = System.getProperty("user.dir") + "/" + System.getProperty("SCREENSHOT_FOLDER") + description.getMethodName() + "_failure.png";
    try {
        File scrFile = driver.getScreenshotAs(OutputType.FILE);
        File testScreenshot = new File(fullFileName);
        FileUtils.copyFile(scrFile, testScreenshot);
        logger.info("Screenshot stored to {}", testScreenshot.getAbsolutePath());
        logger.info("PAGE SOURCE:");
        logger.info(driver.getPageSource());
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}
 
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();
    }
}
 
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();
    }
}
 
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();
    }
}
 
源代码29 项目: JGiven   文件: Html5AppTest.java
@Test
@Issue( "#274" )
public void a_thumbnail_is_shown_for_image_attachments() 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().the_HTML_Report_Generator_is_executed();
    when().the_page_of_scenario_$_is_opened( 1 );
    then().an_element_with_a_$_class_exists( "jgiven-html-thumbnail" )
        .and().the_image_is_loaded();
}
 
源代码30 项目: hifive-pitalium   文件: PtlWebDriver.java
/**
 * スクリーンショットを撮影し、{@link BufferedImage}として取得します。
 *
 * @return 撮影したスクリーンショット
 */
protected BufferedImage getScreenshotAsBufferedImage() {
	try {
		LOG.debug("[getScreenshot start]");
		byte[] data = getScreenshotAs(OutputType.BYTES);
		LOG.debug("[getScreenshot finished]");
		LOG.debug("[ImageIO.read start]");
		BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
		LOG.debug("[ImageIO.read finished]");
		return image;
	} catch (IOException e) {
		throw new TestRuntimeException("Screenshot capture error", e);
	}
}
 
 类所在包
 类方法
 同包方法