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?
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(...);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With