http://www.technicalpage.net/search/label/SQL

Take Screenshot

This code takes 5 screenshots(incrementing number each time screenshot is taken ) and saves in a folder as "jpg".
You need to add a jar "commons io" for this coding.

package regressionTest.pkgName;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
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;
import com.google.common.io.Files;

public class ClassName {

       static AtomicInteger atomicInteger = new AtomicInteger();

       public static void main(String[] args) throws Exception {

              System.setProperty("webdriver.chrome.driver", "D:\\drivers\\chromedriver.exe");
              // Initialize browser.
              WebDriver driver = new ChromeDriver();
              driver.manage().window().maximize();

              // Screenshot#1
              driver.get("http://www.google.com");
              Thread.sleep(5000);
              takeScreenshot(driver);

              // Screenshot#2
              driver.findElement(By.xpath("//a[text()='Store']")).click();
              Thread.sleep(5000);
              takeScreenshot(driver);

              // Screenshot#3
              driver.findElement(By.xpath("//button[text()='Phones']")).click();
              Thread.sleep(5000);
              takeScreenshot(driver);

              // Screenshot#4
              driver.findElement(By.xpath("//button[text()='Connected Home']")).click();
              Thread.sleep(5000);
              takeScreenshot(driver);

              // Screenshot#5
              driver.findElement(By.xpath("//a[text()='Gaming']")).click();
              Thread.sleep(5000);
              takeScreenshot(driver);

              driver.quit();
       }
      
       // To count number of times a method is called
       public static int getMethodInvocationCount() {
              return atomicInteger.incrementAndGet();
       }

// Method to take screenshot.
       public static void takeScreenshot(WebDriver driver) throws Exception {

              int scnShotNumer = getMethodInvocationCount();// counts number of times this method is called

              TakesScreenshot scrShot = ((TakesScreenshot) driver);
             
              // Call getScreenshotAs method to create image file
               File sourcercFile = (File) scrShot.getScreenshotAs(OutputType.FILE);
             
              // Move image file to new destination
              File destinationFile = new File("D:\\ScreenShotTest\\ScreenshotIMG" + scnShotNumer + ".jpg");
             
              // Copy file to destination
              FileUtils.copyFile(sourcercFile, destinationFile);

       }
}

No comments:

Post a Comment