0

リンクの配列があり、次のコードはリンクの配列内の各リンクを開くことになっています。

var x; var i = 0;

casper.start(URL, function() {
    x = links.split(" "); // now x is an array of links
});

casper.then(function() {
    this.each(x, function() { 
        this.thenOpen((partialURL + x[i]), function() {
            this.echo(this.getTitle()); // display the title of page
            i++; // change the link being opened
        });
    });
});

casper.run();

問題は、最初のリンクを開き、そのリンクを何度も開き続けることです。まるでi変わらない。

CasperJS の例の 1 つには、Twitter フォロワーの場合、各 Twitter フォロワーのリンクが開かれるという同じ問題がありましたが、常に 1 つの名前 (リストの最後の名前) が表示されます。

次に例を示します。

var users = ['subelsky','bmorejs'];
var casper = require('casper').create();

var idx,data,user;
var length = users.length;

casper.start();

for (idx=0; idx < length; idx++) {
    user = users[idx];

    casper.thenOpen('http://mobile.twitter.com/' + user,function() {
        data = this.evaluate(function(location) {
            return document.querySelector('div.profile td.stat.stat-last div.statnum').innerText;
        });
        this.echo(user + ": " + data);
    });
}

casper.run();

出力は次のようにbmorejs: 2861 followersなりますbmorejs: 503 followers

これは変更できますか?

4

1 に答える 1

1

の関数に入る前にすべてのリンクを実行しthenOpen、代わりにリンクを開くだけのようです。それは簡単な修正です。

i++;ステートメントをメソッドの上に移動するだけthenOpenで、新しいリンクが開く前に確実に変更されます。また、 の初期値を に変更して、i実行-1時にすぐi++;にスキップしないようにします。1

コードは次のように変更されます。

var x; var i = -1;          

casper.start(URL, function() {
    x = links.split(" "); // now x is an array of links
});

casper.then(function() {
    this.each(x, function() { 
        i++; // change the link being opened (has to be here specifically)
        this.thenOpen((partialURL + x[i]), function() {
            this.echo(this.getTitle()); // title should now be different
        });
    });
});

casper.run();
于 2013-07-31T13:16:16.137 に答える