Taking a screenshot is very easy in selenium. It is supported in almost all the web browser drivers.
The driver instance is casted into a TakesScreenshot type and a file can be obtained. The returned file is saved in the temporary folder with a alphanumeric name. The file can be copied to the results folder using FileUtils class. and renamed to what we want. In the below example it is renamed to Error with time appended to it.
File screenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("C:\\Users\\Krishna\\Desktop\\Error" + (new Date().getTime()) +".png"));
public String extractScreenShot(WebDriverException e) {
Throwable cause = e.getCause();
if (cause instanceof ScreenshotException) {
return ((ScreenshotException) cause).getBase64EncodedScreenshot();
}
return null;
}
File screenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("C:\\Users\\Krishna\\Desktop\\Error" + (new Date().getTime()) +".png"));
RemoteWebDriver is used to run tests in remote browsers. They can also be used in the local system. The advantage of remotewebdriver class is the exceptions often have an attached screenshot encoded as BASE64 png. Most of the exceptions are implementing the Screenshot exception.
The code to use this feature is.
Throwable cause = e.getCause();
if (cause instanceof ScreenshotException) {
return ((ScreenshotException) cause).getBase64EncodedScreenshot();
}
return null;
}
This obtained string can be decoded using Java classes.
byte b1[]=Base64.decodeBase64(extractScreenshot(e));
FileWriter f=new FileWriter("test.png");
f.write(b1.toString());
This is how you save the screenshots taken in the remote desktop in your local system.
Comments
Post a Comment