使用PhantomJS访问多个URL评估错误

时间:2017-02-26 13:00:13

标签: phantomjs

我有这个漂亮的代码,所有我想在访问之间暂停,所以我添加了一个' setinterval',但这不起作用:

var page = require('webpage').create();

// the urls to navigate to
var urls = [
    'http://blogger.com/',
    'https://github.com/',
    'http://reddit.com/'
                ];
    var i = 0;

// the recursion function
var genericCallback = setInterval(function () {
    return function (status) {
        console.log("URL: " + urls[i]);
        console.log("Status: " + status);
        // exit if there was a problem with the navigation
        if (!status || status === 'fail') phantom.exit();

        i++;

        if (status === "success") {

            //-- YOUR STUFF HERE ---------------------- 
            // do your stuff here... I'm taking a picture of the page
            page.render('example' + i + '.png');
            //-----------------------------------------

            if (i < urls.length) {

                // navigate to the next url and the callback is this function (recursion)
                page.open(urls[i], genericCallback());

            } else {
                // try navigate to the next url (it is undefined because it is the last element) so the callback is exit
                page.open(urls[i], function () {
                    phantom.exit();
                });
            }
        }
    };
},2000);

// start from the first url
page.open(urls[i], genericCallback());

我得到错误的屏幕截图: enter image description here 也许有人可以帮助我并治愈这段代码?因为我是JS和PhantomJS的新手,所以任何帮助都是合情合理的。 我从另一个stackoverflow回答中得到了这段代码 - Using Multiple page.open in Single Script 但我无法对作者发表评论,因为我没有50个声誉

1 个答案:

答案 0 :(得分:1)

它应该是这样的:

var page = require('webpage').create();

var urls = ['http://blogger.com/','https://github.com/','http://reddit.com/'];
var i = 0;

function OpenPage(){
    setTimeout(function(){
        page.open(urls[i], function(status) {
            if (status == 'success') {
                    page.render('example' + i + '.png');
            }
            i++;
            if(i <= urls.length - 1){ 
                OpenPage();
            }else{
               phantom.exit();
            }
        });
    },2000);
}

OpenPage();