Taking Screenshots with Selenium for Java
Taking Screenshots with Selenium for Java
Learn how to take a screenshot in Selenium for Java
To take a screenshot, we need to cast our driver object to a TakesScreenshot object.
Let me show you how to do that.
How to Use the TakeScreenshot Class in Selenium
In parentheses, we want to add the class (TakesScreenshot), and then outside of the parentheses we’ll specify driver. And we’re going to store this in a variable. Let’s call it var camera. Great.
Now with this camera, we can have access to a method called getScreenshotAs, and this will take the screenshot with the output type that we specify.
So, the output type is an enum, and we can say camera.getScreenshotAs(OutputType.FILE) specifying it as FILE. This will save it as a file.
We want to store this in a variable, so let’s say File, and we’ll call it “screenshot”. Perfect, this is all we need to take the screenshot.
However, this is going to store that screenshot in an obscure location. Let’s move this to a place that we can easily find.
How to Specify Destination for Saving Screenshots with Selenium
Inside of my project here, I have a folder called resources and another folder called images. I want the screenshot to be saved here in my images folder.
We’re going to say Files and notice I’m using the com.google.common.io package. So, I’m going to say Files.move().
Inside of this move, we’re going to say, take the screenshot that we have stored there. And we want to move this to a new File() location. Now we’re going to specify the path, which can be relative. We’re going to say “resources/images”, and then we’re going to give that file a name. So, we’ll say, “resources/images/page.png”. Perfect.
Notice here, we do have a little compilation error.
If we hover here, it says that we have an unhandled exception, and that exception is an IOException. We need to wrap this in a try catch block.
So, we’ll say try.move the file. And in case of an IOException, go ahead and catch it and just printStackTrace to the console.
That’s it, that’s all we need to take the screenshot. Let’s go ahead and run it just so that you can see the screenshot that’s taken.
Our test has passed, and we look under here in our folders. Yep. Now we have this “page.png” file. And see, here we have a screenshot.
Resources
- Git Repo – ScreenshotTests.java
Schedule a free Applitools Demonstration
Request DemoHere’s the code sample from our tutorial on how to take a screenshot in Selenium for Java