Java Code Examples for org.openqa.selenium.TakesScreenshot

The following examples show how to use org.openqa.selenium.TakesScreenshot. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * �����Խ�����н�ͼ
 * @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 2
@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 3
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;
    }
}
 
Example 4
Source Project: twse-captcha-solver-dl4j   Source File: Downloader.java    License: 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 Project: sahagin-java   Source File: FluentLeniumAdapter.java    License: 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 6
Source Project: openvidu   Source File: OpenViduEventManager.java    License: Apache License 2.0 6 votes vote down vote up
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;
	}
}
 
Example 7
Source Project: test-samples   Source File: BaseTest.java    License: 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 8
@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?
}
 
Example 9
Source Project: selenium   Source File: EventFiringWebDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 11
Source Project: neodymium-library   Source File: AI.java    License: 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 12
Source Project: neodymium-library   Source File: VisualAssertion.java    License: 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 13
/**
 * 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 14
Source Project: NetDiscovery   Source File: SeleniumUtils.java    License: Apache License 2.0 6 votes vote down vote up
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();
        }
    }
 
Example 15
Source Project: hsac-fitnesse-fixtures   Source File: SeleniumHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
/**
 * 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 17
Source Project: edx-app-android   Source File: NativeAppDriver.java    License: 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 18
Source Project: seleniumtestsframework   Source File: ScreenshotUtil.java    License: 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 19
Source Project: apicurio-registry   Source File: SeleniumProvider.java    License: 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 20
Source Project: testng-cucumber   Source File: CucumberRunner.java    License: MIT License 5 votes vote down vote up
@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);

}
 
Example 21
Source Project: gaia   Source File: SeleniumIT.java    License: Mozilla Public License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 22
Source Project: vividus   Source File: DelegatingWebDriverTests.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 23
Source Project: coteafs-selenium   Source File: ScreenAction.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 24
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 25
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 26
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 27
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 28
Source Project: base-framework   Source File: Selenium2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 截屏成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) {
	}
}
 
Example 29
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 30
Source Project: selenium   Source File: CaptureScreenshotToString.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}