selenium之截图 初级教程 java版

selenium常用操作(3)

一、窗口截图

窗口截图也是我们常用的操作,一般都是截取当前窗口的截图。截图用到:

File file =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(file, new File("截图.png"));

这注意我们需要导入一个jar包,commons-io.jar

下面大家看一下我的源码吧。

package com.ls;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;

import java.io.File;
import java.io.IOException;

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 org.testng.annotations.AfterTest;

public class NewTest
{
     //定义全局变量
    WebDriver dr;
    String url;
    
  @Test
  public void f()
  {
      //你要访问的页面的地址也就是网址    这里以Csdn为例
      url="http://blog.csdn.net/qq_38318622";
      //使用get方法来打开这个网址的页面
      dr.get(url);

      File file = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
      try {
        FileUtils.copyFile(file, new File("截图.png"));
    } catch (IOException e1) {
        
        e1.printStackTrace();
    }
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
  @BeforeTest
  public void beforeTest()
  {
      //设置谷歌浏览器的驱动位置   当然也可以不设置那么  你就要将这个驱动也加入到你的系统变量中
     System.setProperty("webdriver.chrome.driver", "C:\\\\Users\\\\Administrator\\\\Desktop\\\\谷歌驱动\\\\chromedriver.exe");
    
     //因为我们要使用ChromeDriver来控制浏览器  所以在这里我们要new一个driver
     dr=new ChromeDriver();
     dr.manage().window().maximize();  
  }

  @AfterTest
  public void afterTest()
  {

      dr.quit();
  }

}


再来看一下我们的截图。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值