[robot]Phantomjs打開網頁截圖範例

  • 596
  • 0

摘要:[robot]Phantomjs打開網頁截圖範例

基本js範例:


var page = require('webpage').create();
page.open('http://www.google.com', function(status) {
    page.viewportSize = { width: 800, height: 600 }; 				
	console.log("Status: " + status);	
	console.log("Rendering png... ");		
	setTimeout(function(){
        //page.render('output.png');    
		page.render('output.png');    
		//等待3秒,網頁js特效跑完之後才儲存圖片
    }, 3000);
	
    //網頁特效跑完2秒之後,關閉網頁(所以是5000-2000)
	setTimeout(function(){
        phantom.exit();
    }, 5000);
	
});

基本js範例的CommandLine使用方式:

phantomjs.exe taipeiCityDistPic.js

網址從command line傳入的js範例:


var page = require('webpage').create();
//取得commandline的參數
var args = require('system').args;
page.open(args[1], function(status) {
    page.viewportSize = { width: 800, height: 600 }; 				
	console.log("Status: " + status);	
	console.log("Rendering png... ");		
	setTimeout(function(){
        //page.render('output.png');    
		page.render(args[2]);    
		//等待20秒,網頁js特效跑完之後才儲存圖片
    }, 20000);
	
    //網頁特效跑完3秒之後,關閉網頁(所以是23000-20000)
	setTimeout(function(){
        phantom.exit();
    }, 23000);
	
});

網址從command line傳入的CommandLine使用方式:

phantomjs MyJs.js "http://www.google.com" myPic.png

 

利用Server端程式碼呼叫phantomJS的方式(ex:c#):


var processStartInfo = new ProcessStartInfo();
processStartInfo.WorkingDirectory = Config.PhantomjsExePath;
processStartInfo.FileName = "cmd.exe";
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;

// set additional properties     
Process proc = Process.Start(processStartInfo);
proc.StandardInput.WriteLine("phantomjs MyJs.js " + "\"" + url + "\"" + " " + Path.GetFileName(localFile));