11

我已经开始在 Windows 上使用 Phantom JS,但是我很难找到有关其功能的文档(可能是我问题的根源)。

使用 Phantom JS 我想做以下事情:

  1. 给它一个本地机器文件夹位置,
  2. 让它导航到该位置并识别 HTML 文件列表,
  3. 一旦该列表被识别为循环 HTML 文件列表并将它们全部转换为 PNG(类似于 rasterize.js 示例的工作方式),其中文件名 gsubs“HTML”和“PNG”。

我确信这可能是可能的,但我找不到 Phantom JS 函数调用:

  1. 获取文件夹中的文件列表和
  2. Phantom JS 中 gsub 和 grep 的格式。
4

1 回答 1

19
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++;
}

希望这可以帮助。有关 FileSystem 调用的更多信息,请查看此页面: http: //phantomjs.org/api/fs/

另外,我想补充一点,我相信 FileSystem 功能仅在 PhantomJS 1.3 或更高版本中可用。请确保运行最新版本。我在 Windows 上使用了 PyPhantomJS,但我确信这在其他系统上也可以正常工作。

于 2011-09-26T00:13:51.410 回答