使用PhantomJS访问多个URL时,评估错误[英] Visiting multiple urls using PhantomJS evaluating Error

问题描述

我有这段漂亮的代码,我只想在访问之间暂停一下,所以我添加了一个"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());

我得到的错误截图:在此处输入图片描述也许有人可以帮助我并修复此代码?因为我是 JS 和 PhantomJS 的新手,所以任何帮助都将不胜感激.我从这里的另一个 stackoverflow 答案中获得了此代码 - 在单个脚本中使用多个 page.open但我不能对作者发表评论,因为我没有 50 声望

推荐答案

应该是这样的:

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();

本文地址:https://www.itbaoku.cn/post/1739990.html