org.openqa.selenium.TakesScreenshot Java Examples

The following examples show how to use org.openqa.selenium.TakesScreenshot. 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: 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 #2
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 #3
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 #4
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 #5
Source File: AI.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 #6
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 #7
Source File: SeleniumUtils.java    From NetDiscovery with 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 #8
Source File: SeleniumHelper.java    From hsac-fitnesse-fixtures with 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 #9
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 #10
Source File: WebDriverScreenCaptureAdapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: EventFiringWebDriverTest.java    From selenium with 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 #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: OpenViduEventManager.java    From openvidu with 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 #14
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 #15
Source File: StatisticDataIT.java    From AisAbnormal with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #16
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 #17
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 #18
Source File: JavaDriverTest.java    From marathonv5 with 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 #19
Source File: Test.java    From webdsl with Apache License 2.0 5 votes vote down vote up
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();
}
  }
 
Example #20
Source File: ScreenshotTest.java    From aws-device-farm-sample-web-app-using-appium with Apache License 2.0 5 votes vote down vote up
@Test
   public void testScreenshot() throws InterruptedException {

Thread.sleep(5000);
driver.get(TEST_URL);
Thread.sleep(5000);
// This will store the screenshot under /tmp on your local machine
String screenshotDir = System.getProperty("appium.screenshots.dir", System.getProperty("java.io.tmpdir", ""));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
screenshot.renameTo(new File(screenshotDir, "device_farm.png"));

   }
 
Example #21
Source File: AllureSelenide.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private static Optional<byte[]> getScreenshotBytes() {
    try {
        return WebDriverRunner.hasWebDriverStarted()
            ? Optional.of(((TakesScreenshot) WebDriverRunner.getWebDriver()).getScreenshotAs(OutputType.BYTES))
            : Optional.empty();
    } catch (WebDriverException e) {
        LOGGER.warn("Could not get screen shot", e);
        return Optional.empty();
    }
}
 
Example #22
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 #23
Source File: ScreenServiceImpl.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void takeScreenshot(Scenario scenario) {
    log.debug("takeScreenshot with the scenario named [{}]", scenario.getName());
    log.debug("size: {}x{}", Context.getDriver().manage().window().getSize().getWidth(), Context.getDriver().manage().window().getSize().getHeight());
    final byte[] screenshot = ((TakesScreenshot) Context.getDriver()).getScreenshotAs(OutputType.BYTES);
    scenario.embed(screenshot, "image/png");
}
 
Example #24
Source File: ScreenshotManager.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
void logBase64Screenshot(WebDriver driver, String fileName) {
    try {
        String screenshotBase64 = ((TakesScreenshot) driver)
                .getScreenshotAs(BASE64);
        log.info("Screenshot (in Base64) at the end of {} "
                + "(copy&paste this string as URL in browser to watch it):\r\n"
                + "data:image/png;base64,{}", fileName, screenshotBase64);
    } catch (Exception e) {
        log.trace("Exception getting screenshot in Base64", e);
    }
}
 
Example #25
Source File: InitialSetupHooks.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Если сценарий завершился со статусом "fail" будет создан скриншот и сохранен в директорию
 * {@code <project>/build/reports/tests}
 *
 * @param scenario текущий сценарий
 */
@After(order = 20)
public void takeScreenshot(Scenario scenario) {
    if (scenario.isFailed() && hasWebDriverStarted()) {
        AkitaScenario.sleep(1);
        final byte[] screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.BYTES);
        scenario.embed(screenshot, "image/png");
    }
}
 
Example #26
Source File: SeleniumWrapper.java    From SeleniumBestPracticesBook with Apache License 2.0 5 votes vote down vote up
public void takeScreenshot() {
  File scrFile = ((TakesScreenshot) selenium).getScreenshotAs(OutputType.FILE);
  try {
    File filename = new File("images", TimeStamp.getTimestamp() + ".png");
    System.out.println("Saving screenshot to " + filename.getAbsolutePath());
    FileUtils.copyFile(scrFile, filename);
  } catch (IOException e) {
    e.printStackTrace();
  }

}
 
Example #27
Source File: UiTestBase.java    From cloud-personslist-scenario with Apache License 2.0 5 votes vote down vote up
private void takeScreenshot() throws IOException {
	final File tempFile = ((TakesScreenshot) driver)
			.getScreenshotAs(OutputType.FILE);
	final String targetName = getClass().getSimpleName() + "."
			+ testName.getMethodName() + ".png";
	final File targetFile = new File(screenshotFolder, targetName);
	FileUtils.copyFile(tempFile, targetFile);
	System.out.println("Screenshot for test " + testName.getMethodName()
			+ " saved in " + targetFile.getAbsolutePath());
}
 
Example #28
Source File: WebRtcRemoteFirefoxTest.java    From webdrivermanager-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    driver.get(
            "https://webrtc.github.io/samples/src/content/devices/input-output/");
    String screenshotBase64 = ((TakesScreenshot) driver)
            .getScreenshotAs(BASE64);
    System.err.println("data:image/png;base64," + screenshotBase64);
}
 
Example #29
Source File: RoundUpSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Метод осуществляет снятие скриншота и прикрепление его к cucumber отчету.
 *
 */
@И("^снят скриншот текущей страницы$")
@And("^screenshot of the current page has been taken$")
public void takeScreenshot() {
    final byte[] screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.BYTES);
    AkitaScenario.getInstance().getScenario().embed(screenshot, "image/png");
}
 
Example #30
Source File: Application.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
@Action(object = ObjectType.APP, desc = "Take Screenshot of the Desktop")
public void takeDesktopScreenShot() {
    try {
        String ssName = Report.getNewScreenShotName();
        File location = new File(FilePath.getCurrentResultsPath() + ssName);
        File srcFile = ((TakesScreenshot) (new EmptyDriver())).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, location);
        Report.updateTestLog(Action, "ScreenShot Taken", Status.PASS, ssName);
    } catch (IOException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        Report.updateTestLog(Action, "Couldn't Take ScreenShot", Status.DEBUG);
    }
}