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

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

源代码1 项目: 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);
}
 
源代码2 项目: 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);
	}
}
 
源代码3 项目: AisAbnormal   文件: StatisticDataIT.java
private void checkCellsAreDisplayedWhenZoomingIn() throws InterruptedException {
    assertCellLayerLoadStatusNoCellsLoaded();

    try {
        WebElement zoomIn = browser.findElement(By.cssSelector("a.olControlZoomIn.olButton"));
        zoomIn.click();
        Thread.sleep(300);
        assertCellLayerLoadStatusNoCellsLoaded();
        zoomIn.click();
        Thread.sleep(300);
        assertCellLayerLoadStatusNoCellsLoaded();
        zoomIn.click();
        Thread.sleep(300);
        assertCellLayerLoadStatusNoCellsLoaded();
        zoomIn.click();
        Thread.sleep(300);
        assertCellLayerLoadStatusNoCellsLoaded();
        zoomIn.click();
        wait.until(ExpectedConditions.textToBePresentInElement(By.id("cell-layer-load-status"), "61 cells loaded, 61 added to map."));
    } catch (Throwable e) {
        if (browser instanceof TakesScreenshot) {
            IntegrationTestHelper.takeScreenshot(browser,"error");
        }
        throw e;
    }
}
 
源代码4 项目: 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();
	}
}
 
源代码5 项目: 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;
    }
}
 
源代码6 项目: openvidu   文件: OpenViduEventManager.java
public void waitUntilEventReaches(String eventName, int eventNumber, int secondsOfWait, boolean printTimeoutError)
		throws Exception {
	CountDownLatch eventSignal = new CountDownLatch(eventNumber);
	this.setCountDown(eventName, eventSignal);
	try {
		if (!eventSignal.await(secondsOfWait * 1000, TimeUnit.MILLISECONDS)) {
			String screenshot = "data:image/png;base64," + ((TakesScreenshot) driver).getScreenshotAs(BASE64);
			System.out.println("TIMEOUT SCREENSHOT");
			System.out.println(screenshot);
			throw (new TimeoutException());
		}
	} catch (InterruptedException | TimeoutException e) {
		if (printTimeoutError) {
			e.printStackTrace();
		}
		throw e;
	}
}
 
源代码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;
}
 
@Override
public byte[] captureScreen() {
    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;
    }
    // TODO test should not fail when taking screen capture fails?
}
 
源代码9 项目: selenium   文件: EventFiringWebDriverTest.java
@Test
public void getScreenshotAs() {
  final String DATA = "data";
  WebDriver mockedDriver = mock(WebDriver.class, withSettings().extraInterfaces(TakesScreenshot.class));
  WebDriverEventListener listener = mock(WebDriverEventListener.class);
  EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener);

  doReturn(DATA).when((TakesScreenshot)mockedDriver).getScreenshotAs(OutputType.BASE64);

  String screenshot = ((TakesScreenshot)testedDriver).getScreenshotAs(OutputType.BASE64);
  assertThat(screenshot).isEqualTo(DATA);

  InOrder order = Mockito.inOrder(mockedDriver, listener);
  order.verify(listener).beforeGetScreenshotAs(OutputType.BASE64);
  order.verify((TakesScreenshot)mockedDriver).getScreenshotAs(OutputType.BASE64);
  order.verify(listener).afterGetScreenshotAs(OutputType.BASE64, screenshot);
  verifyNoMoreInteractions(mockedDriver, listener);
}
 
源代码10 项目: 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();
    }
}
 
源代码11 项目: neodymium-library   文件: AI.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;
    }
}
 
源代码12 项目: 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;
    }
}
 
/**
 * 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;
}
 
源代码14 项目: NetDiscovery   文件: SeleniumUtils.java
public static void taskScreenShot(WebDriver driver,WebElement element,String pathName) {

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

        try {
            //获取元素在所处frame中位置对象
            Point p = element.getLocation();
            //获取元素的宽与高
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            //矩形图像对象
            Rectangle rect = new Rectangle(width, height);
            BufferedImage img = ImageIO.read(srcFile);
            BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
            ImageIO.write(dest, "png", srcFile);
            IOUtils.copyFile(srcFile, new File(pathName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
源代码15 项目: 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;
}
 
源代码16 项目: 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);
    }
}
 
源代码17 项目: 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();
	}
}
 
源代码18 项目: 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 "";
}
 
源代码19 项目: apicurio-registry   文件: SeleniumProvider.java
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());
    }
}
 
源代码20 项目: testng-cucumber   文件: CucumberRunner.java
@AfterClass(alwaysRun = true)
public void takeScreenshot() throws IOException {
	File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	File trgtFile = new File(System.getProperty("user.dir") + "//screenshots/screenshot.png");
	trgtFile.getParentFile().mkdir();
	trgtFile.createNewFile();
	Files.copy(scrFile, trgtFile);

}
 
源代码21 项目: gaia   文件: SeleniumIT.java
void takeScreenshot() {
    var file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    System.out.println(file.getAbsolutePath());
    try {
        FileUtils.copyFileToDirectory(file, new File("./target"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码22 项目: 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));
}
 
源代码23 项目: coteafs-selenium   文件: ScreenAction.java
@Override
public File saveScreenshot (final String path) {
    final String msg = "Capturing screenshot and saving at [{}]...";
    LOG.i (msg, path);
    try {
        final File source = ((TakesScreenshot) this.driver).getScreenshotAs (OutputType.FILE);
        final File destination = new File (path);
        copyFile (source, destination);
        return destination;
    } catch (final IOException e) {
        LOG.e ("Error while saving screenshot.", e);
        handleError (FILTER_PKG, e).forEach (LOG::e);
    }
    return null;
}
 
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();
    }
}
 
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();
    }
}
 
源代码28 项目: base-framework   文件: Selenium2.java
/**
 * 截屏成png文件,复制到目标文件。源文件存放于临时目录,在JVM退出时自动删除.
 */
public void snapshot(String basePath, String outputFileName) {
	File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
	File targetFile = new File(basePath, outputFileName);
	try {
		FileUtils.copyFile(srcFile, targetFile);
	} catch (IOException ioe) {
	}
}
 
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();
    }
}
 
源代码30 项目: selenium   文件: CaptureScreenshotToString.java
@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
  if (driver instanceof TakesScreenshot) {
    TakesScreenshot tsDriver = (TakesScreenshot) driver;
    return tsDriver.getScreenshotAs(OutputType.BASE64);
  }
  throw new UnsupportedOperationException("WebDriver does not implement TakeScreenshot");
}
 
 类所在包
 类方法
 同包方法