當前位置: 首頁>>代碼示例>>Java>>正文


Java TakesScreenshot類代碼示例

本文整理匯總了Java中org.openqa.selenium.TakesScreenshot的典型用法代碼示例。如果您正苦於以下問題:Java TakesScreenshot類的具體用法?Java TakesScreenshot怎麽用?Java TakesScreenshot使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


TakesScreenshot類屬於org.openqa.selenium包,在下文中一共展示了TakesScreenshot類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: captureScreenshot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
private static String captureScreenshot(WebDriver driver, String screenshotPath, String ScreenshotName) {

		String destinationPath = null;
		try {
			File destFolder = new File(screenshotPath);
			
			destinationPath = destFolder.getCanonicalPath() + "/" + ScreenshotName + ".png";
		
			// Cast webdriver to Screenshot
			TakesScreenshot screenshot = (TakesScreenshot) driver;

			File sourceFile = screenshot.getScreenshotAs(OutputType.FILE);

			FileUtils.copyFile(sourceFile, new File(destinationPath));

		} catch (Exception e) {
			System.out.println("Error capturing screenshot...\n" + e.getMessage());
			e.printStackTrace();
		}
		return destinationPath;
	}
 
開發者ID:anilpandeykiet,項目名稱:POM_HYBRID_FRAMEOWRK,代碼行數:22,代碼來源:ReportManager.java

示例2: screenshot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
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();
    }
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:20,代碼來源:JavaDriverTest.java

示例3: createScreenshot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
public static void createScreenshot(String fileName) {

		if (SeleniumDriver.getInstance() instanceof TakesScreenshot) {

			File fileSrc = ((TakesScreenshot) SeleniumDriver.getInstance()).getScreenshotAs(OutputType.FILE);

			try {
				File destFile = new File(String.format(SCREENSHOTS_FORMAT, fileName));
				FileUtils.copyFile(fileSrc, destFile);
				LOG.info("[Screenshot] " + destFile.getAbsolutePath());
			} catch (IOException e) {
				;
			}
		}

	}
 
開發者ID:entelgy-brasil,項目名稱:zucchini,代碼行數:17,代碼來源:ScreenshotHook.java

示例4: afterTest

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
/**
 * <p>
 * Takes screen-shot if the scenario fails
 * </p>
 *
 * @param scenario will be the individual scenario's within the Feature files
 * @throws InterruptedException Exception thrown if there is an interuption within the JVM
 */
@After()
public void afterTest(Scenario scenario) throws InterruptedException {
    LOG.info("Taking screenshot IF Test Failed");
    System.out.println("Taking screenshot IF Test Failed (sysOut)");
    if (scenario.isFailed()) {
        try {
            System.out.println("Scenario FAILED... screen shot taken");
            scenario.write(getDriver().getCurrentUrl());
            byte[] screenShot = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenShot, "image/png");
        } catch (WebDriverException e) {
            LOG.error(e.getMessage());
        }
    }
}
 
開發者ID:usman-h,項目名稱:Habanero,代碼行數:24,代碼來源:ScreenShotHook.java

示例5: setScreenshot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
@AfterMethod
public void setScreenshot(ITestResult result) {
  if (!result.isSuccess()) {
    try {
      WebDriver returned = new Augmenter().augment(webDriver);
      if (returned != null) {
        File f = ((TakesScreenshot) returned).getScreenshotAs(OutputType.FILE);
        try {
          FileUtils.copyFile(f,
              new File(SCREENSHOT_FOLDER + result.getName() + SCREENSHOT_FORMAT));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (ScreenshotException se) {
      se.printStackTrace();
    }
  }
}
 
開發者ID:ViliamS,項目名稱:XPathBuilder,代碼行數:20,代碼來源:TestBase.java

示例6: tearDown

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
@After
public void tearDown(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            logger.info("Test failed, taking screenshot");
            byte[] screenshot = ((TakesScreenshot) new Augmenter().augment(getAppiumDriver()))
                    .getScreenshotAs(OutputType.BYTES);
            scenario.embed(screenshot, "image/png");
        }
        catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        }
        catch (ClassCastException cce) {
            cce.printStackTrace();
        }
    }
    application.tearDown();
}
 
開發者ID:HotwireDotCom,項目名稱:bdd-test-automation-for-mobile,代碼行數:19,代碼來源:SetupTeardownSteps.java

示例7: afterScenario

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
@After
public void afterScenario( Scenario scenario ) throws Exception
{
    try
    {
        attachLog();

        if( scenario.isFailed() )
        {
            try
            {
                scenario.write( "Current Page URL is " + getDriver().getCurrentUrl() );
                byte[] screenshot;
                try
                {
                    screenshot = ( ( TakesScreenshot ) getDriver() ).getScreenshotAs( OutputType.BYTES );
                } catch( ClassCastException weNeedToAugmentOurDriverObject )
                {
                    screenshot = ( ( TakesScreenshot ) new Augmenter().augment( getDriver() ) ).getScreenshotAs( OutputType.BYTES );
                }
                String relativeScrnShotPath = takeScreenshot().substring(takeScreenshot().indexOf("screenshots"));
                Reporter.addScreenCaptureFromPath(relativeScrnShotPath, getDriver().getCurrentUrl());
            } catch( WebDriverException somePlatformsDontSupportScreenshots )
            {
                System.err.println( somePlatformsDontSupportScreenshots.getMessage() );
            }
        }
    } finally
    {
        closeDriverObjects();
    }
}
 
開發者ID:hemano,項目名稱:cucumber-framework-java,代碼行數:33,代碼來源:StartingSteps.java

示例8: main

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
public static void main(String[] args) {
    String phantomJsPath = "D:/Program Files/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe";
    String savePath = "D:/screenshot.png";
    Gospy.custom()
            .setScheduler(Schedulers.VerifiableScheduler.custom()
                    .setPendingTimeInSeconds(60).build())
            .addFetcher(Fetchers.TransparentFetcher.getDefault())
            .addProcessor(Processors.PhantomJSProcessor.custom()
                    .setPhantomJsBinaryPath(phantomJsPath)
                    .setWebDriverExecutor((page, webDriver) -> {
                        TakesScreenshot screenshot = (TakesScreenshot) webDriver;
                        File src = screenshot.getScreenshotAs(OutputType.FILE);
                        FileUtils.copyFile(src, new File(savePath));
                        System.out.println("screenshot has been saved to " + savePath);
                        return new Result<>();
                    })
                    .build())
            .build().addTask("phantomjs://http://www.zhihu.com").start();
}
 
開發者ID:ZhangJiupeng,項目名稱:Gospy,代碼行數:20,代碼來源:SeleniumDemo.java

示例9: takeScreenShot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
static Consumer<WebDriver> takeScreenShot() {
    return (webDriver) -> {
        //take Screenshot
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            outputStream.write(((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES));
            //write to target/screenshot-[timestamp].jpg
            final FileOutputStream out = new FileOutputStream("target/screenshot-" + LocalDateTime.now() + ".png");
            out.write(outputStream.toByteArray());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
}
 
開發者ID:Java-Publications,項目名稱:vaadin-016-helloworld-14,代碼行數:17,代碼來源:WebDriverFunctions.java

示例10: createScreenShot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
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;
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:21,代碼來源:SeleniumDriver.java

示例11: onError

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
@Override
protected void onError(Description description, Throwable testFailure) throws Throwable {
    super.onError(description, testFailure);
    if(Objects.nonNull(screenshotProvider)) {
        WebDriver webDriver = seleniumProvider.getWebDriver();
        if (webDriver instanceof TakesScreenshot) {
            BufferedImage screenshot = screenshotProvider.takeScreenshot(webDriver);

            File destFile = TestReportFile.forTest(description).withPostix(".png").build().getFile();
            ImageIO.write(screenshot, "PNG", destFile);

            LOGGER.info("Saved screenshot as " + destFile.getAbsolutePath());
        } else {
            testFailure.addSuppressed(
                    new RuntimeException(
                            "Could not take screenshot, since webdriver is not a " +
                                    TakesScreenshot.class.getName() + " instance as expected. Actual class is " +
                                    webDriver.getClass().getName()));
        }
    } else {
        LOGGER.info("Due to SreenshotProvider is not specified, no screenshot is taken");
    }
}
 
開發者ID:willhaben,項目名稱:willtest,代碼行數:24,代碼來源:ScreenshotRule.java

示例12: captureAndDisplayScreenShot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
/**
 * This method captures the screenshot and places it in the execution report
 **/
public static void captureAndDisplayScreenShot(WebDriver ldriver,
		ExtentTest eTest) {
	Date dtnow2 = new Date();
	String strStartDate2 = dtnow2.toString().replace(":", "_");
	String strDateStamp2 = strStartDate2.replace(" ", "_");
	File src = ((TakesScreenshot) ldriver).getScreenshotAs(OutputType.FILE);
	try {
		String screenshotPath = dirPath + "_" + strDateStamp2 + ".png";
		FileUtils.copyFile(src, new File(screenshotPath));
		eTest.addScreenCaptureFromPath(screenshotPath);
	} catch (IOException e) {
		System.out.println(e.getMessage());
	}
}
 
開發者ID:AnujDasari,項目名稱:Actitime-Framework,代碼行數:18,代碼來源:ExtentReport.java

示例13: captureScreenshot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
/**
 * This method captures a screenshot
 **/
public static void captureScreenshot(WebDriver driver, String screenshotName) {
	try {
		TakesScreenshot ts = (TakesScreenshot) driver;
		File source = ts.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(source, new File(dirPath + "/ " + screenshotName
				+ "_" + strDateStamp

				+ ".png"));
		String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
		System.setProperty(ESCAPE_PROPERTY, "false");
		URL path = new File(dirPath + "/ " + screenshotName + "_"
				+ strDateStamp + ".png").toURI().toURL();
		String test = "<a href=" + path + "> click to open screenshot of "
				+ screenshotName + "</a>";
		Reporter.log(screenshotName + test + "<br>");
		Reporter.log("<br>");
	}

	catch (Exception e) {
		System.out.println("Exception while taking screenshot "
				+ e.getMessage());
	}
}
 
開發者ID:AnujDasari,項目名稱:Actitime-Framework,代碼行數:27,代碼來源:ReportNGReport.java

示例14: saveScreenShot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
/**
 * Save screenshot to file.
 * 
 * @param fileName
 */
public static void saveScreenShot(String fileName){
	File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
	try {

		Path destPath = Paths.get(
				Logger.getLogger().getLogDirPath().toString() 
				+ "/" + fileName);

		FileUtils.copyFile(scrFile, new File(destPath.toString()));
		logger.log("Saved screenshot: " + destPath.toString());

	} catch (IOException e) {
		logger.logLines(e.getStackTrace().toString());
		logger.log("Failed to save screenshot!");
		System.out.println();
	}
}
 
開發者ID:danrusu,項目名稱:mobileAutomation,代碼行數:23,代碼來源:Driver.java

示例15: taskScreenShot

import org.openqa.selenium.TakesScreenshot; //導入依賴的package包/類
public static void taskScreenShot(WebDriver driver,File saveFile){
	if(saveFile.exists()){
		saveFile.delete();
	}
	byte[] src=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);//.FILE);linux下非root用戶,java創建臨時文件存在問題
	log.info("截圖文件字節長度"+src.length);
	try {
		FileUtils.writeByteArrayToFile(saveFile, src);
	} catch (IOException e) {
		e.printStackTrace();
		log.error("截圖寫入失敗",e);
	}
}
 
開發者ID:xbynet,項目名稱:crawler,代碼行數:14,代碼來源:WindowUtil.java


注:本文中的org.openqa.selenium.TakesScreenshot類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。