When we test a website and face bugs we need screenshot of the output to suggest to the developer to fix the issue. Automated testing is usually evidenced by Screenshots and logs. But how to save screenshots with timestamp in the file name using Selenium?
In this example we will follow these steps:
1. Access the url “https://time.is/India”
2. Take the screenshot of the page which is showing indian time
3. Con the california time
4. Take the screenshot
5. Exit
Code:
package testing; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Screenshot { public static WebDriver driver; public void openbrowser(String url) throws IOException { //Open the browser System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe"); driver = new ChromeDriver(); // Maximize the window size driver.manage().window().maximize(); // Open the url driver.get(url); // Call the screenshot method to take a screenshot captureScreenshot("screenshot1",".png"); //Click on the button for open the next page driver.findElement(By.id("time-6")).click(); //Again call the method to capture the screenshot of next page captureScreenshot("screenshot2",".png"); //Close the browser driver.quit(); } public static void main(String[] args) throws IOException { Screenshot call = new Screenshot(); call.openbrowser("https://time.is/India"); } // Take screenshot method Private void captureScreenshot(String fileName,String extension)throws IOException { // Take the screenshot and store as file format File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Open the current date and time String timestamp = new SimpleDateFormat("yyyy_MM_dd__hh_mm_ss").format(new Date()); //Copy the screenshot on the desire location with different name using current date and time FileUtils.copyFile(scrFile, new File("C:/shots/" + fileName+" "+timestamp+extension)); }
CODE DESCRIPTION:
1. File scrFile = ((TakesScreenshot)driver)
–This statement converts the webdriver object into the screenshot.
2. getScreenshotAs(OutputType.FILE);
–This method captures the screenshot.
3. String timestamp = new SimpleDateFormat(“yyyy_MM_dd__hh_mm_ss”).format(new Date());
–It returns the current date and time.
4. FileUtils.copyFile(scrFile, new File(“C:/shots/” + fileName+” “+timestamp+extension));
–It saves the screenshot to the desired location and we use the timestamp variable to save the screenshot with a different name every time
Screenshots:
After running the script it saves the screenshots like this: