Can any one explain Screenshot in Selenium?

☆樱花仙子☆ 提交于 2020-01-23 05:37:04

问题


WebDriver driver = new FirefoxDriver();

driver.get("http://www.google.com/");

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Can any tell me that

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE) 

getScreenShotAs is the method in the TakesScreenshot Interface......

(TakesScreenshot)driver, What it refers to??? can you please explain little bit?


回答1:


The WebDriver interface does not contain the getScreenshotAs() method, because it is possible to have a webdriver unable of taking screenshots - for example the in-memory drivers that don't render the page at all, like HtmlUnitDriver.

In order to have the method, the driver must implement the TakesScreenshot interface which makes it capable to ... well ... take screenshots.

Therefore, you must tell the program somehow that you want to take a screenshot and that you are absolutely sure you can do so. That's what the (TakesScreenshot)driver part is for. In Java, it's called casting and it literally translates to "I know that this driver instance is able to take a screenshot, please cast it to TakesScreenshot type."

If your cast succeeds, everything is fine and the driver object will be cast at run-time to an instance of TakesScreenshot. If your cast fails, however, you'll get a ClassCastExcepion at run-time.

Some examples:

// We already know this is ok, because FirefoxDriver implements (IS-A) TakesScreenshot.
WebDriver driver = new FirefoxDriver();
TakesScreenshot screenshottingDriver = (TakesScreenshot)driver;

// This will fail at run-time, because HtmlUnitDriver does not implement TakesScreenshot;
WebDriver driver = new HtmlUnitDriver();
TakesScreenshot screenshottingDriver = (TakesScreenshot)driver;

// You can use the `instanceof` operator to check:
if (driver instanceof TakesScreenshot) {
    // we can be sure we can take screenshots, the cast will be safe
    ((TakesScreenshot)driver).getScreenshotAs(...);
}



回答2:


As you may read here it indicates that the driver can take a screenshot. It is necessary to do the casting because the WebDriver interface does not contain the getScreenshotAs method although it is implemented by most of the classes that implement that interface like FirefoxDriver.



来源:https://stackoverflow.com/questions/21877839/can-any-one-explain-screenshot-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!