使用javascript循环访问phantomjs中的url数组

时间:2015-09-01 14:48:21

标签: javascript arrays for-loop phantomjs

我试图让我的代码循环遍历一系列网址但却陷入困境。

这段代码只是在phantomjs中运行,并输出所请求的url和任何主要资源对象的重定向。

我想使用数组作为此过程的输入,如:

var pageUrl = [
'http://www.google.com',
'http://www.facebook.com'
];

这是原来的

var sys = require('system');
var pageUrl = 'http://www.google.com';


console.log("Requested URL: " + pageUrl);



var renderPage = function (url) {
    var page = require('webpage').create();

    page.onNavigationRequested = function(url, type, willNavigate, main) {

        if (main && url!=pageUrl) {
            console.log("Redirected URL: " + url)
        }
    };



    page.open(url, function(status) {
            if ( status !== 'success' ) {
                phantom.exit(1);
            } else {
                setTimeout(function() {
                    phantom.exit(0);
                }, 0);
            }
        });
};


renderPage(pageUrl);

1 个答案:

答案 0 :(得分:4)

var urls = [
'http://www.google.com',
'http://www.facebook.com'
];


function process() {
    if (urls.length == 0) {
        phantom.exit();
    } else {
        //remove the first item of an array
        url = urls.shift();
        //open a page
        page = require('webpage').create();

        //store the requested url in a separate variable
        var currentUrl = url


        page.open(url, onFinishedLoading)

        page.onNavigationRequested = function(url, type, willNavigate, main) {
            console.log('\n' + currentUrl + '\nredirecting to \n' + url);
        }

    }
}

function onFinishedLoading(status) {

    console.log(status);
    page.release();
    process();
}

process();
相关问题