How to take screenshots in Selenium
Posted By : Mohd Nawaz Hussain | 31-Oct-2022
In our Automation Script, we generally take screenshots to justify whether scripts are passed or not.
There are a few ways to take screenshots in Selenium. The simplest way is to use the WebDriver’s takesScreenshot() method. This method will take a screenshot of the current page and save it as a PNG file.
For this, you will need to create a WebDriver instance. Below is an example to create a Web Driver instance.
WebDriver driver = new ChromeDriver();
Next, you will need to navigate to the URL of the page that you want to take a screenshot using below Line of code.
Finally, you will need to take the screenshot. Below is the code written.
TakesScreenshot ts = (TakesScreenshot) driver;
File srcFile = ts.getScreenshotAs(OutputType.FILE);
File destFile = new File("./screenshots/firstShot.png");
Files.copy(srcFiles , destFile);
This code will take a screenshot of the current page and save it to a file. You can then use this file to save the screenshot or do whatever else you need to do with it.
You can also use the getScreenshotAs() method to take a screenshot and save it in another format, such as JPG or PDF.
If you want to take a screenshot of a specific element on the page, you can use the WebElement’s getScreenshotAs() method. This method will take a screenshot of the element and save it as a PNG file.
This can be useful if you want to capture a specific element on a page, such as a button or an image.
To take a screenshot, you will first need to locate the web element you want to capture. This can be done using the Selenium WebDriver's findElement() method. Once you have located the element, you can call the getScreenshotAs() method on it.
The getScreenshotAs() method takes a single parameter, which is the file format you want to save the screenshot in. The most common file formats are PNG and JPG.
Once you have called the getScreenshotAs() method, the screenshot will be saved to the file format you specified. You can then view the screenshot by opening the file in an image viewer.
Finally, you can use the TakesScreenshot interface to take a screenshot. This interface provides methods for taking screenshots and for retrieving the screenshots as an InputStream.
To take a screenshot in Selenium, you will need to do the following:
- Import the org.openqa.selenium.OutputType class.
- Import the org.openqa.selenium.TakesScreenshot interface.
- Use the WebDriver’s takesScreenshot() or getScreenshotAs() method to take a screenshot.
- Use the TakesScreenshot interface to take a screenshot.
- Retrieve the screenshot as an InputStream.
Mohd Nawaz Hussain
Mohd possesses more than 1 year of experience as a Quality Analyst. He has good knowledge in both automation and manual testing. He has hands-on experience in Design Automation Frameworks and Automation Test Scripts.