WebDriver进行屏幕截图

转自 http://blog.csdn.net/iceryan/article/details/8566628

例: 打开百度首页 ,进行截图

[java] view plaincopy
 
  1. package com.example.tests;  
  2. import java.io.File;  
  3. import org.apache.commons.io.FileUtils;  
  4. import org.junit.*;  
  5. import org.openqa.selenium.*;  
  6. import org.openqa.selenium.ie.InternetExplorerDriver;  
  7. public class Selenium2 {  
  8.     @Test  
  9.     public void testTakesScreenshot() {  
  10.         WebDriver driver = new InternetExplorerDriver();  
  11.         driver.get("http://www.baidu.com");  
  12.         try {  
  13.             File srcFile = ((TakesScreenshot)driver).  
  14.                     getScreenshotAs(OutputType.FILE);  
  15.             FileUtils.copyFile  
  16.             (srcFile,new File("d:\\screenshot.png"));  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }   
  20.           driver.close();  
  21.         }  
  22. }  

 

 

TakesScreenshot接口提供了getScreenshotAs()方法来捕捉屏幕。上面的例子中,我们指定了OutputType.FILE作为参数传递给getScreenshoAs()方法,告诉它将截取的屏幕以文件形式返回。

 

如果使用的是RemoteWebDriver() ,则方法应该如下

首先启动selenium java -jar selenium-server-standalone-2.25.0.jar 

 

[java] view plaincopy
 
  1. package com.example.tests;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.net.MalformedURLException;  
  5. import java.net.URL;  
  6. import org.apache.commons.io.FileUtils;  
  7. import org.junit.*;  
  8. import org.openqa.selenium.*;  
  9. import org.openqa.selenium.remote.*;  
  10. public class Selenium2 {  
  11.     @Test  
  12.     public void testRemoteWebDriverScreenShot() {  
  13.         //指定使用的浏览器  
  14.         DesiredCapabilities capability = DesiredCapabilities.internetExplorer();  
  15.         WebDriver driver = null;  
  16.         try {  
  17.             driver = new RemoteWebDriver( //我使用localhost来测试  
  18.                     new URL("http://localhost:4444/wd/hub"), capability);  
  19.         } catch (MalformedURLException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.         driver.get("http://www.sina.com.cn");  
  23.         //对远程系统进行截图  
  24.         driver = new Augmenter().augment(driver);   
  25.         File scrFile =    
  26.           ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
  27.         try {  
  28.             FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));  
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.         }  
posted @ 2015-03-06 02:04  princessd8251  阅读(189)  评论(0)    收藏  举报