javascript - 使用javascript遍历phantomjs中的网址数组

标签 javascript arrays for-loop phantomjs

我正在尝试让我的代码循环遍历一系列url,但被卡住了。

这部分代码仅在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);

最佳答案

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

关于javascript - 使用javascript遍历phantomjs中的网址数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334673/

相关文章:

javascript - 在 Bootstrap 导航栏中添加时显示动态添加的导航链接

javascript - 使用自定义函数在 d3.js 中创建元素

java - 用Java写一个float数组到文件

javascript - 为什么 obj 不可迭代

c# - 如何生成for循环

javascript - jQuery 存在 url 验证在 Codeigniter 中不起作用

javascript - 当 v-for 与对象的属性一起使用时,将 v-model 与复选框一起使用

arrays - 使用 mongoose 在 mongodb 中保存多个字段数组

javascript - 分解 PHP/Typescript 数组的第 2 层元素

python - 使用 python 3 在 for 循环内的同一行中插入 sleep() 和 print()