2011-09-23 48 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

相关问题