如何使用casperjs / phantomjs保存当前网页?

时间:2014-07-05 01:49:31

标签: javascript phantomjs casperjs

有没有办法使用casperjs或phantomjs保存当前网页? 我试图获取html并将其保存到文件中。但是生成的文件与当时的屏幕截图(使用casper.capture)有很大不同。有没有办法保存当前的网页?

2 个答案:

答案 0 :(得分:10)

Andrey Borisko建议使用磁盘缓存来检索资源。我的解决方案效率不高,但您不需要解压缩文本文件。

在使用resource.received事件处理程序注册后,我使用XMLHttpRequest检索所有资源。然后我将资源过滤为图像,CSS和字体。目前的限制是,包含.././之类的远程资源路径未得到正确处理。

我使用getHTML检索当前页面内容并迭代所有捕获的资源,以使用随机生成的文件名替换标记中使用的路径,该路径由完整资源URL的一部分标识。文件扩展名是根据资源的内容类型创建的。它使用mimeType from this gist进行转换。

由于CSS文件可能包含背景图像或字体,因此必须在保存到磁盘之前对其进行处理。提供的loadResource函数会加载资源,但不会保存它。

由于要下载资源的XMLHttpRequest,必须使用--web-security=false标志调用脚本:

casperjs script.js --web-security=false

<强>的script.js

var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;

fs.removeTree(resourceDirectory);

casper.on("remote.message", function(msg){
    this.echo("remote.msg: " + msg);
});

casper.on("resource.error", function(resourceError){
    this.echo("res.err: " + JSON.stringify(resourceError));
});

casper.on("page.error", function(pageError){
    this.echo("page.err: " + JSON.stringify(pageError));
});

casper.on("downloaded.file", function(targetPath){
    if (debug) this.echo("dl.file: " + targetPath);
});

casper.on("resource.received", function(resource){
    // don't try to download data:* URI and only use stage == "end"
    if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
        if (resource.contentType == "text/css") {
            cssResources.push({obj: resource, file: false});
        }
        if (resource.contentType.indexOf("image/") == 0) {
            imgResources.push({obj: resource, file: false});
        }
        if (resource.contentType.indexOf("application/x-font-") == 0) {
            fontResources.push({obj: resource, file: false});
        }
    }
});

// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
    "use strict";
    this.checkStarted();
    var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
    return cu.decode(this.base64encode(url, method, data));
};


function escapeRegExp(string) {
    // from https://stackoverflow.com/a/1144788/1816580
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function replaceAll(find, replace, str) {
    // from https://stackoverflow.com/a/1144788/1816580
    return str.replace(find, replace);
}

var wrapFunctions = [
    function wrapQuot1(s){
        return '"' + s + '"';
    },
    function wrapQuot2(s){
        return "'" + s + "'";
    },
    function csswrap(s){
        return '(' + s + ')';
    }
];

function findAndReplace(doc, resources, resourcesReplacer) {
    // change page on the fly
    resources.forEach(function(resource){
        var url = resource.obj.url;

        // don't download again
        if (!resource.file) {
            // set random filename and download it **or** call further processing which in turn will load ans write to disk
            resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
            if (typeof resourcesReplacer != "function") {
                if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
                casper.download(url, resource.file, "GET");
            } else {
                resourcesReplacer(resource);
            }
        }

        wrapFunctions.forEach(function(wrap){
            // test the resource url (growing from the back) with a string in the document
            var lastURL;
            var lastRegExp;
            var subURL;
            // min length is 4 characters
            for(var i = 0; i < url.length-5; i++) {
                subURL = url.substring(i);
                lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
                if (doc.match(lastRegExp)) {
                    lastURL = subURL;
                    break;
                }
            }
            if (lastURL) {
                if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
                doc = replaceAll(lastRegExp, wrap(resource.file), doc);
            }
        });
    });
    return doc;
}

function capturePage(){

    // remove all <script> and <base> tags
    this.evaluate(function(){
        Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
            scr.parentNode.removeChild(scr);
        });
        Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
            scr.parentNode.removeChild(scr);
        });
    });

    // TODO: remove all event handlers in html

    var page = this.getHTML();
    page = findAndReplace(page, imgResources);
    page = findAndReplace(page, cssResources, function(cssResource){
        var css = casper.loadResource(cssResource.obj.url, "GET");
        css = findAndReplace(css, imgResources);
        css = findAndReplace(css, fontResources);
        fs.write(cssResource.file, css, "wb");
    });
    fs.write("page.html", page, "wb");
}

casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
    this.echo("DONE");
    this.exit();
});

神奇发生在findAndReplacecapturePage是完全同步的,所以它可以放在任何地方而不会有太多头痛。

mimetype.js

的网址

答案 1 :(得分:0)

不,我不认为有一种简单的方法可以做到这一点,因为幻影并不支持以 mht 格式(Render as a .mht file #10117)呈现页面。我相信这就是你想要的。 因此,完成此任务需要一些工作。我做了类似的事情,但我正在这样做,我有一个渲染的HTML代码,我通过phantomjs渲染成image / pdf。我必须先清理文件,它对我来说很好。

所以,我认为你需要做的是:

  • 删除所有js调用,例如script标记或onload属性等。

  • 如果您可以从本地访问css,图像等资源(并且您不需要对您抓取页面的域进行身份验证),那么您需要更改{的相对路径{1}}属性为绝对加载图像/等。

  • 如果您在打开页面时无法访问资源,那么我认为您需要实施similar script以便在phantomjs加载页面时下载这些资源,然后重定向{ {1}}属性到该文件夹​​或者可能使用数据uri。 您可能还需要更改css文件中的链接。

这将显示您目前缺少的图像\字体和样式。

我确定还有更多积分。如果您在看到我的代码后需要更多信息,我会更新答案。