微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

窗口 – 使用Phantom JS将文件夹中的所有HTML文件转换为PNG

我已经开始在 Windows上使用Phantom JS,但是在查找有关其功能的文档(可能是我的问题的根源)方面有一些困难.

使用Phantom JS我想做以下:

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

我确定这可能是可能的,但是我无法找到Phantom JS函数调用

>获取文件夹中的文件列表
> Phantom JS中gsub和grep的格式.

解决方法

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调用的更多信息,请查看此页面https://github.com/ariya/phantomjs/wiki/API-Reference

此外,我想补充说,我相信FileSystem功能仅在PhantomJS 1.3或更高版本中可用.请确保运行latest版本.我使用PyPhantomJS Windows,但我确信这将工作,而不妨碍其他系统.

原文地址:https://www.jb51.cc/js/151003.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐