永夜若离

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

WebDriver实现屏幕截屏

一般情况下当自动化测试过程中有需要特别关注的业务流程点,我们可以将对于的业务界面截图下来,以便后续进行进一步分析

webdriver支持截图功能,我们可以实现一个通用的类,用于业务代码的调用。

代码如下:

 1 import org.openqa.selenium.OutputType;
 2 import org.openqa.selenium.TakesScreenshot;
 3 import java.io.File;
 4 import java.io.IOException;
 5 import org.apache.commons.io.FileUtils;
 6 import org.openqa.selenium.WebDriver;
 7 import org.openqa.selenium.firefox.FirefoxDriver;
 8 import org.openqa.selenium.WebElement;
 9 import org.openqa.selenium.By;
10 
11 public class Snapshot {
12 
13     public static void screenshot(TakesScreenshot screendriver , String filename){
14         
15 /*利用screendriver的getScreenshotAs(OutputType.FILE)方法生成File实例srcfile*/
16         File srcfile = screendriver.getScreenshotAs(OutputType.FILE);
17         
18         try{
19 /*FileUtils的copyFileToDirectory方法可以实现文件的复制,指定File实例和需要复制的文件路径*/
20             FileUtils.copyFileToDirectory(srcfile, new File(System.getProperty("user.dir")+"\\"+filename));
21         }catch(IOException e){
22             e.printStackTrace();
23         }finally{
24             System.out.println("shot the screen sucessfully");
25         }
26         
27     }
28 
29 
30 public static void main(String[] args) {
31         // TODO Auto-generated method stub
32         /*设置火狐浏览器的系统路径*/
33         System.setProperty("webdriver.firefox.bin", 
34                 "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
35         
36 /*new一个WebDriver 对象并打开搜狗主页*/
37         WebDriver driver = new FirefoxDriver();
38         String URL = "http://www.sogou.com";
39         driver.navigate().to(URL);
40         //等待2s
41         try {
42             Thread.sleep(2000);
43         } catch (InterruptedException e) {
44             // TODO Auto-generated catch block
45             e.printStackTrace();
46         }
47         //执行截图
48         screenshot((TakesScreenshot)driver, "sogou.png");
49         //找到id为query的元素,其实是搜狗主页的搜索框
50         WebElement element = driver.findElement(By.id("query"));
51         //清理
52         element.clear();
53 //输入字符串
54         element.sendKeys("南京");
55         //等待两s
56         try {
57             Thread.sleep(2000);
58         } catch (InterruptedException e) {
59             // TODO Auto-generated catch block
60             e.printStackTrace();
61         }
62         //执行截图
63         screenshot((TakesScreenshot)driver, "nanjing.png");
64         
65 //点击搜索按钮
66         driver.findElement(By.id("stb")).click();
67         try {
68             Thread.sleep(2000);
69         } catch (InterruptedException e) {
70             // TODO Auto-generated catch block
71             e.printStackTrace();
72         }
73 
74 //再次执行截图
75         screenshot((TakesScreenshot)driver, "newpage.png");
76     }
77 }

最终我们将会在工程目录下找到截图的目录:

posted on 2017-01-05 18:12  永夜若离  阅读(214)  评论(0)    收藏  举报