Web drivers provide two different ways to take a screenshot
Example 1st:-
Note:- Download the Jar file of org.apache.commons.io and add to the project.
Link
Download here
package scs;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
public class Screenshotexample {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://eroomrent.in/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d://screenshot.png"));
driver.close();;
}
}
Example 2nd:-
using Robot class
package scs;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenshotByRobot {
public static void main(String[] args) throws IOException, AWTException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.eroomrent.in/");
driver.manage().window().maximize();
Robot robot = new Robot();
//Rectangle Class Initialization
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
//Defining Output files destination
File destFile = new File("d:\\scr\\screenshot");
//Screenshot Capture
BufferedImage img = robot.createScreenCapture(rect);
//Writing image to destination with its formats
ImageIO.write(img, "png", destFile);
driver.close();
driver.quit();
}
}
POST Answer of Questions and ASK to Doubt