Take Screenshot in Selenium WebDriver: When I am working as manual testers, that time when we are testing an application, and if we found any bug then we are taking the screenshot of that and send that to a developer so that they can go through the bug and try to fix. As a part of testing, the screenshot is played a major role because without that its too difficult to influence the developer.
Similarly, when we are automate something in selenium webdriver, we may also come across bugs, and in that case, we need to capture the screenshots. So for taking screenshot selenium provides this feature. With this, we can be debugging the errors and also get to know which step the test goes to fail.
How To Take Screenshot
Selenium webdriver has the built-in functionality to take the screenshot of the web page and its quite easy well. Because selenium webdriver has an interface called TakesScreenshot, which can capture the screenshot during the execution of the selenium script.
In the TakesScreenshot interface, we have a method called getScreenshotAs(), which can capture the screenshot and store that in a specified location by us. By using this method, we can take the screenshot of various browsers like Chrome, Firefox, IE, Opera, etc. using their respective web-drivers.
The WebDriver interface extends the TakesScreenshot, and all browser drivers like ChromeDriver, FirefoxDriver, InternetExplorerDriver, EdgeDriver, OperaDriver these all are implementing the TakesScreenshot interface, that’s why in all browser we can take the screenshot.
Note The Selenium webdriver extending the TakesScreenshot interface and by using the getScreenshotAs() method, this method only capable of capturing the visible area of the web page and not the full page.
import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class SeleniumScreenshotTest { public static void main(String[] args) throws IOException { System.setProperty(“webdriver.chrome.driver” , “C:\\drivers\\chromedriver.exe”); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get(“https://www.softwaretestingo.com”); // down casting WebDriver to use getScreenshotAs method. TakesScreenshot ts= (TakesScreenshot)driver; // capturing screen shot as output type file File screenshotSRC= ts.getScreenshotAs(OutputType.FILE); // Defining path and extension of image String path=System.getProperty(“user.dir”)+”/ScreenCapturesPNG/”+testStepsName+System.currentTimeMillis()+”.png”; // copying file from temp folder to desired location File screenshotDest= new File(path); FileUtils.copyFile(screenshotSRC, screenshotDest); driver.quit(); } }
Explanation Of The Above Code
WebDriver driver = new ChromeDriver();
In the above statement we have upcasted the chromedriver object to webdriver, but for capture the screenshot we need to downcast the chromedriver object driver to TakesScreenshot interface.
TakesScreenshot ts= (TakesScreenshot)driver; File screenshotSRC= ts.getScreenshotAs(OutputType.FILE);
In the above statement, the OutputType is an interface which can provide options to take the screenshot in different types such as FILE, BASE64, BYTES, and class. But out of those types, the file type is mostly used.
path=System.getProperty("user.dir")+"/ScreenCapturesPNG/"+testStepsName+System.currentTimeMillis()+".png";
When webdriver takes the screenshot, it stores in the temp folder. Once the execution is over the file also got deleted. That’s why we need to copy the screenshot in a permanent folder, so for that in the above statement we are mentioned the permanent folder which is ScreenCapturesPNG with the file name.
File screenshotDest= new File(path);
In this statement, we are creating a file where we mentioned where it should be stored with a specific name.
How Do You Take Screenshot of The Entire Page
For taking the full page screenshot, we can take the help of the third-party tools like AShot to take the whole page screenshot or a specific element screenshot. Now we are going to discuss the AShot tools, and these tools have a rich feature like:
- Take a specific area of a page
- Do scroll and take a screenshot
- In case you have an infinite scroll page, you can set timeouts
- Ignore are during the screenshot
- Change orientation or change resolution
Let us go through with a simple program and try to understand how it works.
How To Make a Screenshot using AShot
For this program, we have used two extra jar files, and that is Apache Commons IO, and another one is Yandex QATools AShot WebDriver Utility.
For different screenshot, we have created different methods. Here are the methods:
- screenshotGetScreenShotAs: It takes the viewable screen’s screenshot. Like a print screen operation.
- screenshotWebElement2: It takes an element screenshot by cropping element size from an entire viewable area’s screenshot.
- screenshotWebElement3: It takes an element screenshot by using the web element directly from an entire viewable area’s screenshot.
- screenshotEntirePageAshot: It takes all (entire) screenshot of a website from top to bottom.
Before starting to write the code, please create the screenshots folders under your project folder, as shown below.
Note: Folder name in the sample source code are written for Windows OS, in case you use Unix system, please change them accordingly.
import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import ru.yandex.qatools.ashot.shooting.ShootingStrategies; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ScreenShotTest { public WebDriver driver; private String url = "https://www.amazon.com"; //Current Directory private String currentDir = System.getProperty("user.dir"); //GetScreenShot Method Directory and Image File private File getSreenShotMethodImageFile = new File (currentDir + "\\ScreenShots\\GetScreenShotMethod\\amazonscreenshot.png"); //Element Screenshot Directory and Image File private File webElementImageFile = new File(currentDir + "\\ScreenShots\\Ashot\\WebElement\\logo.png" ); //Entirepage ScreenShot Directory and Image File private File entirePageImageFile = new File(currentDir + "\\ScreenShots\\Ashot\\EntirePage\\entirepage.png" ); //Setup Driver @BeforeClass public void setupTest() { driver = new ChromeDriver(); //Navigate to URL driver.navigate().to(url); driver.manage().window().maximize(); } @Test (priority = 0) public void screenshotGetScreenShotAs() throws IOException { //Take Screenshot of viewable area File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //Write Screenshot to a file FileUtils.copyFile(scrFile, getSreenShotMethodImageFile); } @Test (priority = 1) public void screenshotWebElement2() throws IOException { //Find the element WebElement logo = driver.findElement(By.cssSelector(".nav-logo-link .nav-logo-base")); // Get viewable area's screenshot File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); BufferedImage fullImg = ImageIO.read(screenshot); // Get the location of element on the page Point point = logo.getLocation(); // Get width and height of the element int eleWidth = logo.getSize().getWidth(); int eleHeight = logo.getSize().getHeight(); // Crop element from viewable area's screenshot to get element's screenshot BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight); ImageIO.write(eleScreenshot, "png", screenshot); //Write Screenshot to a file FileUtils.copyFile(screenshot, webElementImageFile); } @Test (priority = 1) public void screenshotWebElement3() throws IOException { //Find the element WebElement logo = driver.findElement(By.cssSelector("#nav-logo")); Screenshot elementScreenShot = new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, logo); try { ImageIO.write(elementScreenShot.getImage(), "PNG", webElementImageFile); } catch (IOException e) { e.printStackTrace(); } } @Test (priority = 2) public void screenshotEntirePageAshot() throws IOException { //Take Screenshot of entire page by AShot Screenshot entirePageScreenShot = new AShot(). shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver); //Write Screenshot to a file ImageIO.write(entirePageScreenShot.getImage(),"PNG", entirePageImageFile); } //Close Driver @AfterClass public void quitDriver() { driver.quit(); } }
Taking Full Page Screenshot Using JavaScript
Above we have discussed how to take the full page screenshot with the help of using third-party tools. Here we are going to learn another alternative way to take the full page screenshot with the help of JavaScript.
Here is the program:
import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class CaptureFullWebPage { public static String CaptureScreenShotWithTestStepName(WebDriver driver, String testStepsName) { try { // down casting WebDriver to use getScreenshotAs method. TakesScreenshot ts= (TakesScreenshot)driver; // capturing screen shot as output type file File screenshotSRC= ts.getScreenshotAs(OutputType.FILE); // Defining path and extension of image String path=System.getProperty("user.dir")+"/ScreenCapturesPNG/"+testStepsName+System.currentTimeMillis()+".png"; // copying file from temp folder to desired location File screenshotDest= new File(path); FileUtils.copyFile(screenshotSRC, screenshotDest); return path; } catch(Exception e) { System.out.println("Some exception occured." + e.getMessage()); return ""; } } public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("http://www.softwaretestingo.com/"); // Down casting driver to JavascriptExecutor JavascriptExecutor js = (JavascriptExecutor) driver; // It returns height of view part. You can say it as page height. When you click on page down key // Page scroll by one page. long pageHeight= (long)js.executeScript("return window.innerHeight"); System.out.println("Page height: "+pageHeight); // It is how much you can scroll. It is height if you scroll, you will reach to bottom of page. long scrollableHeight= (long)js.executeScript("return document.body.scrollHeight"); System.out.println("Total scrollable height: "+scrollableHeight); // Finding number of pages. Adding 1 extra to consider decimal part. int numberOfPages=(int) (scrollableHeight/pageHeight)+1; System.out.println("Total pages: "+numberOfPages); // Now scrolling page by page for(int i=0;i<numberOfPages;i++) { CaptureFullWebPage.CaptureScreenShotWithTestStepName(driver, "Page "+(i+1)); js.executeScript("window.scrollBy(0,"+pageHeight+")"); Thread.sleep(2000); } } }
How to Take Screenshot of a Web element
Steps to take a screenshot element:
- Open the browser and navigate to Url:
- Find the element and Store the element as ‘element.’
- Take the screenshot of the full page, with output type as FILE
- Get the location of the element using the getLocation() method in selenium from the stored element.
- Get the size of the element using the getSize() method from selenium
- Create an object for the BufferedImage class using Image.read(imageStored), and this class will be helpful for image processing operations.
- Use getSubimage method from BufferedImage, pass coordinates and width and height for sub-image. sub-image is nothing but our element. Store the processed image on your machine
import java.awt.image.BufferedImage; import java.io.File; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.Point; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class GetElementSCreenShot { public static void main(String[] args) throws Exception { // set the geckodriver.exe property System.setProperty("webdriver.gecko.driver", "C:/PATH/geckodriver.exe"); WebDriver driver =new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://chercher.tech/selenium-webdriver-sample"); //Locate Image element to capture a screenshot. WebElement element = driver.findElement(By.xpath("//input")); //Capture entire page screenshot as File. //Used TakesScreenshot, OutputType Interface of selenium and File class of java to capture a screenshot of the entire page. File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); //Used selenium Point class to get x y coordinates of Image element. //get location(x y coordinates) of the element. Point point = element.getLocation(); int xcordinate = point.getX(); int ycordinate = point.getY(); //Used selenium getSize() method to get height and width of element. //Retrieve width of element. int imageWidth = element.getSize().getWidth(); //Retrieve height of element. int imageHeight = element.getSize().getHeight(); //Reading full image screenshot. BufferedImage img = ImageIO.read(screen); //cut Image using height, width and x y coordinates parameters. BufferedImage destination = img.getSubimage(xcordinate, ycordinate, imageWidth, imageHeight); ImageIO.write(destination, "png", screen); //save Image screenshot In D: drive. FileUtils.copyFile(screen, new File("D:\\screenshotOfElement.png")); } }
How to Capture Screenshot Different Name Using TestNg?
package com.selenium.basics; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class CaptureScreenshotWithDifferentName { static WebDriver driver; public static void main(String[] args) throws InterruptedException, IOException { CaptureScreenshotWithDifferentName obj=new CaptureScreenshotWithDifferentName(); driver=new FirefoxDriver(); driver.get("http://www.softwaretestingblog.in"); Thread.sleep(3000); obj.getScreenShots("manoj"); driver.close(); } public void getScreenShots(String abc) throws IOException { TakesScreenshot ts=(TakesScreenshot)driver; File src=ts.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("G:\\Base_Workspace\\Luna\\Selenium\\Screenshots\\SC" + abc+getTimeStamp() + ".png")); //Files are Stored in G:\Base_Workspace\Luna\Selenium\Screenshots } public String getTimeStamp() { String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()); return timestamp; } }
Nice explanation.