- Learn Selenium
- Unmesh Gundecha Carl Cocchiaro
- 367字
- 2021-06-24 13:25:41
Taking screenshots
Taking a screenshot of a web page is a very useful capability of WebDriver. This is very handy when your test case fails, and you want to see the state of the application when the test case failed. The TakesScreenShot interface in the WebDriver library is implemented by all of the different variants of WebDriver, such as Firefox Driver, Internet Explorer Driver, Chrome Driver, and so on.
The TakesScreenShot capability is enabled in all of the browsers by default. Because this is a read-only capability, a user cannot toggle it. Before we see a code example that uses this capability, we should look at an important method of the TakesScreenShot interface—getScreenshotAs().
The API syntax for getScreenshotAs() is as follows:
public X getScreenshotAs(OutputType target)
Here, OutputType is another interface of the WebDriver library. We can ask WebDriver to output the screenshot in three different formats : BASE64, BYTES (raw data), and FILE. If you choose the FILE format, it writes the data into a .png file, which will be deleted once the JVM is killed. So, you should always copy that file into a safe location so that it can be used for later reference.
The return type is a specific output that depends on the selected OutputType. For example, selecting OutputType.BYTES will return a bytearray, and selecting OutputType.FILE will return a file object.
Depending on the browser used, the output screenshot will be one of the following, in order of preference:
- The entire page
- The current window
- A visible portion of the current frame
- The screenshot of the entire display containing the browser
For example, if you are using Firefox Driver, getScreenshotAs() takes a screenshot of the entire page, but Chrome Driver returns only the visible portion of the current frame.
It's time to take a look at the following code example:
@BeforeMethod
public void setup() throws IOException {
System.setProperty("webdriver.chrome.driver",
"./src/test/resources/drivers/chromedriver");
driver = new ChromeDriver();
driver.get("http://demo-store.seleniumacademy.com/");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("./target/screenshot.png"));
}
In the preceding code, we used the getScreenshotAs() method to take the screenshot of the web page and save it to a file format. We can open the saved image from the target folder and examine it.