03_ Coding:. Code Selenium Screenshot
//convert WebDriver object to ScreenShoot
TakesScreenshot takesScreenshot = ((TakesScreenshot)driver);
//take screenshot as file
File src =takesScreenshot.getScreenshotAs(OutputType.FILE);
//define the file location and name
File destination= new File("screenshot\\2.png");
//copy file to destination
FileUtils.copyFile(src,destination);
//12HR AM/PM -->03-28-2024_08-11-53 PM
String name =DateTimeFormatter.ofPattern("MM-dd-yyyy_hh-mm-ss a").format(LocalDateTime.now());
TakesScreenshot obj = (TakesScreenshot) driver;
File src = obj.getScreenshotAs(OutputType.FILE);
File dest = new File("screenshot\\screenshot_"+name+".png");
FileUtils.copyFile(src,dest);
// or
// 24HR --> 03-28-2024_20:11:53
String name1= DateTimeFormatter.ofPattern("MM-dd-yyyy_HH mm ss").format(LocalDateTime.now());
FileUtils.copyFile(((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE),new File("screenshot\\screenshot_"+name1+".png"));
//Note : dont use : or other specical charecter file does not support those charectors
Simple method
***************************************************************************
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();
// generate file name based on time
String fileName = DateTimeFormatter.ofPattern("mm-dd-yy_hh-mm-ss").format(LocalDateTime.now());
TakesScreenshot sn = (TakesScreenshot) driver;
File file = sn.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("screenshots/sn_" + fileName + ".png"));
driver.quit();
// Make the separate method and call
*****************************************************************************
public class Base {
public void takeScreenShot(WebDriver driver, String pageName) {
try {
// generate file name based on time
String fileName = DateTimeFormatter
.ofPattern("MM-dd-yyyy_hh-mm-ss")
.format(LocalDateTime.now());
TakesScreenshot sn = (TakesScreenshot) driver;
File file = sn.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("screenshots/" + pageName + fileName + ".png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Call the method in Test
public class SleniumWIthIbuildDriver extends Base {
WebDriver driver;
@Test
public void setUp() throws IOException {
driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();
takeScreenShot(driver, "home2_");
driver.quit();
}
}
Comments
Post a Comment