使用phantomjs解析多个页面

时间:2015-09-21 13:14:25

标签: phantomjs

我已经制作了一个解析页面中所有URL的代码。接下来,我想从每个已解析的URL <div class="holder"><a href="THESE URL-s"></a></div>获取一个href,并将其输出到一个文件并用逗号分隔。

到目前为止,我已经制作了这段代码。它能够找到需要解析的所有URL,并将它们收集到名为output2.txt的逗号分隔文件中。

var resourceWait  = 300,
maxRenderWait = 10000,
url = 'URL TO PARSE HREF-s FROM';
var page          = require('webpage').create(),
count         = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };

function doRender() {
    var fs = require('fs');
    var path = 'output2.txt';
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        fs.write(path,page.evaluate(function() {
            return $('.urlDIV').find('a')
            .map(function() {
            return this.href;})
            .get()
            .join(',');
        }), 'w');

        phantom.exit()
    });
}

page.onResourceRequested = function (req) {
    count += 1;

    clearTimeout(renderTimeout);
};

page.onResourceReceived = function (res) {
    if (!res.stage || res.stage === 'end') {
        count -= 1;

        if (count === 0) {
            renderTimeout = setTimeout(doRender, resourceWait);
        }
    }
};

page.open(url, function (status) {
    if (status !== "success") {

        phantom.exit();
        } else {
        forcedRenderTimeout = setTimeout(function () {
            console.log(count);
            doRender();
        }, maxRenderWait);
    }
});

提前致谢,

马尔蒂阿赫

0 个答案:

没有答案
相关问题