WebDriver拾级而上·之十二 截图selenium-webdriver
--好的测试人员都会截得一手好图,就跟骨灰级宅男定会吟得一手好诗一般。 截取页面全图,不管页面有多长。
Java代码
package com.test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test_ShotScreen {
public static void main(String[] args) throws IOException, InterruptedException{
String url = "http://www.51.com";
//打开chrome
WebDriver dr = new ChromeDriver();
dr.get(url);
//这里等待页面加载完成
Thread.sleep(5000);
//下面代码是得到截图并保存在D盘下
File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
//FileUtils.copyFile(screenShotFile, new File("D:/test.png"));
FileUtils.copyFile(screenShotFile, new File("D:\\AutoScreenCapture\\" + getCurrentDateTime()+ ".jpg"));
dr.quit();
}
public static String getCurrentDateTime(){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");//设置日期格式
//System.out.println(df.format(new Date()));
return df.format(new Date());
}
}
--方法
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public void takeScreenShot(String name){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("c:\\Learning\\"+ name));
} catch (IOException e) {
e.printStackTrace();
}
}