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();
}
}
再来看一下我们的截图。