Sunday, August 6, 2017

Selenium Code Snippets





Following HTML code demonstrates how to take screenshots for the tests executed using Selenium. Approach1: Use the Selenium WebDriver


 public static void captureScreenShotSelenium(WebDriver ldriver, String opFileName){
  // Take screenshot and store as a file format             
   File src=((TakesScreenshot)ldriver).getScreenshotAs(OutputType.FILE);           
  try {
   opFileName = (opFileName == null) ? "" : opFileName;
  // now copy the  screenshot to desired location using copyFile method
  FileUtils.copyFile(src, new File("C:/selenium/"+opFileName+System.currentTimeMillis()+".png"));
  System.out.println("Capture Successful!");
  } catch (IOException e)
  {
    System.out.println(e.getMessage()); 
   } 
 }
Approach2: Use Robot package

 
 public static void captureAltPrintScreenPNG(String filepathfull)
    {
     Robot robot;
     Transferable t;
     RenderedImage image;
     File opFile;
     try {
      robot = new Robot();
      robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_PRINTSCREEN);
            robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
            robot.keyRelease(KeyEvent.VK_ALT);
            
            Thread.sleep(1000 * 2);
            
            t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
            image = (RenderedImage)t.getTransferData(DataFlavor.imageFlavor);//UnsupportedFlavorException
            
            opFile = new File(filepathfull);
            boolean isSuccess = ImageIO.write(image, "png", opFile);

            System.out.println(isSuccess+" "+opFile.getCanonicalPath());
            
     }
     catch (AWTException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } catch (UnsupportedFlavorException e) {
   e.printStackTrace();
  }
     finally
     {
      
     }
    }