您的位置:首页 > Web前端 > JavaScript

网页截图方案selenium/phantomjs

2016-06-28 20:36 531 查看
web项目中有时候会需要将网页截图并保存,这里介绍两种解决方案,使用selenium或phantomjs都可以达到目的。

#使用selenium

需要的相关程序和jar包可以到这里下载:https://pan.baidu.com/s/1c9NGwI

测试代码

import java.io.File;

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 TestSelenium {

public static void main(String[] args) throws InterruptedException {
try {
long start=System.currentTimeMillis();
String URL = "http://www.baidu.com";
System.setProperty("webdriver.chrome.driver","D:\\temp\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //浏览器窗口最大化
driver.get(URL);
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\temp\\baidu_selenium.png"));
driver.close();//关闭浏览器
System.out.println("耗时 "+ (System.currentTimeMillis()-start)+" 毫秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}


网页有滚动条的时候上面的代码只能截取当前屏幕,使用下面的方法可以截取完整的网页。
启动selenium server,cmd命令行下输入:

java -jar F:\selenium\selenium-server-standalone-2.53.0.jar

Selenium selenium = new DefaultSelenium("localhost", 4444, "*firefox", URL);
selenium.start();
selenium.open(URL);
selenium.windowMaximize();
selenium.windowFocus();
selenium.captureEntirePageScreenshot("D:\\temp\\baidu_screenshot.png", "");


使用selenium截图有一个不爽的地方就是它会打开浏览器。

#使用phantomJS
需要的相关程序和jar包可以到这里下载:https://pan.baidu.com/s/1boXRWDL

rasterize.js在phantomjs-2.1.1-windows.zip解压后的examples目录下。

测试代码:

public class TestPhantomjs {

public static void main(String[] args) {
try {
long start=System.currentTimeMillis();
String targetUrl="http://blog.csdn.net/java_zys?viewmode=list";
String targetImg=" d:/temp/csdn_phantomjs.png";
String command = "D:/temp/phantomjs.exe D:/temp/rasterize.js "+targetUrl+targetImg;
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
System.out.println((System.currentTimeMillis()-start)+" 毫秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}


phantomJS有滚动条的情况下页可以截取整个网页,且不需要打开浏览器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息