2011-09-23 51 views
10

我已經開始在Windows上使用Phantom JS,但在查找其功能(可能是我的問題的根源)方面存在一些問題。使用Phantom JS將文件夾中的所有HTML文件轉換爲PNG

使用虛擬JS我想做到以下幾點:

  1. 給它一個本地機文件夾位置,
  2. 有它導航到該位置並識別HTML文件列表中,
  3. 一旦該列表被標識爲HTML文件列表的循環,並將它們全部轉換爲PNG(類似於rasterize.js示例的工作方式),其中文件名gsubs「HTML」和「PNG」。

我敢肯定,這可能是可能的,但我沒能找到幻影JS函數調用:

  1. 獲取文件夾中的文件列表,並
  2. 格式在Phantom JS中用於gsub和grep。

回答

18
var page = require('webpage').create(), loadInProgress = false, fs = require('fs'); 
var htmlFiles = new Array(); 
console.log(fs.workingDirectory); 
var curdir = fs.list(fs.workingDirectory); 

// loop through files and folders 
for(var i = 0; i< curdir.length; i++) 
{ 
    var fullpath = fs.workingDirectory + fs.separator + curdir[i]; 
    // check if item is a file 
    if(fs.isFile(fullpath)) 
    { 
     // check that file is html 
     if(fullpath.indexOf('.html') != -1) 
     { 
      // show full path of file 
      console.log('File path: ' + fullpath); 
      htmlFiles.push(fullpath); 
     } 
    } 
} 

console.log('Number of Html Files: ' + htmlFiles.length); 

// output pages as PNG 
var pageindex = 0; 

var interval = setInterval(function() { 
    if (!loadInProgress && pageindex < htmlFiles.length) { 
     console.log("image " + (pageindex + 1)); 
     page.open(htmlFiles[pageindex]); 
    } 
    if (pageindex == htmlFiles.length) { 
     console.log("image render complete!"); 
     phantom.exit(); 
    } 
}, 250); 

page.onLoadStarted = function() { 
    loadInProgress = true; 
    console.log('page ' + (pageindex + 1) + ' load started'); 
}; 

page.onLoadFinished = function() { 
    loadInProgress = false; 
    page.render("images/output" + (pageindex + 1) + ".png"); 
    console.log('page ' + (pageindex + 1) + ' load finished'); 
    pageindex++; 
} 

希望這helps。有關FileSystem調用的更多信息,請查看此頁面:http://phantomjs.org/api/fs/

另外,我想補充一點,我相信FileSystem函數僅在PhantomJS 1.3或更高版本中可用。請確保運行latest版本。我在Windows上使用了PyPhantomJS,但我相信這樣也可以在其他系統上順利運行。

+0

不知何故,我只是用腳本得到空白的'PNG's。添加'console.log(page.content);'in'page.onLoadFinished'返回''無論想要真正的HTML內容是...任何建議? Phantomjs v1.9.2 – AvL

+0

在你試圖拍攝快照之前,你確定你的頁面已經完全加載嗎? –

+0

我也檢查過「狀態」。看到我的問題:http://stackoverflow.com/questions/19939046/phantomjs-fails-to-open-local-file – AvL

相關問題