1. 程式人生 > >網頁截圖方案selenium/phantomjs

網頁截圖方案selenium/phantomjs

web專案中有時候會需要將網頁截圖並儲存,這裡介紹兩種解決方案,使用selenium或phantomjs都可以達到目的。

#使用selenium

測試程式碼

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

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有滾動條的情況下頁可以擷取整個網頁,且不需要開啟瀏覽器。