2016-05-16 112 views
0

這個問題是similartoothers,但我的問題是更基本。CasperJS循環遍歷每個URL

這是我的代碼:

var links = []; 
var casper = require('casper').create(); 

function getLinks() { 
    var links = document.querySelectorAll('div#mw-content-text table.wikitable tbody tr td i b a'); 
    return Array.prototype.map.call(links, function(e) { 
     return 'https://en.wikipedia.org' + e.getAttribute('href'); 
    }); 
} 

casper.start('https://en.wikipedia.org/wiki/David_Bowie_discography'); 

casper.then(function() { 
    // aggregate results for the 'casperjs' search 
    links = this.evaluate(getLinks); 
}); 

casper.each(links, function (self, link) { 
    self.thenOpen(fullURL, function() { 
     this.echo(this.getTitle() + " - " + link); 
    }); 
}); 

casper.run(); 

我知道,因爲它是從Quickstart複製的links生成,但後來我修改了它打開所有被發現的鏈接。

我得到的是沒有echo'd而不是輸出每個標題,這是我所期望的。這是我如何調用文件:

~ $ casperjs casper-google-disco.js 

回答

4

定盤最終很容易,但我花了年齡找到它沒有任何錯誤,並沒有其他人似乎已觸及這一點。

問題是在調用each之前,links變量未被設置。將each放在then函數內解決了我的問題。

CasperJS樣本中的each.js example有助於確認您可以循環訪問數組而不需要任何IIFE

var links = []; 
var casper = require('casper').create(); 

function getLinks() { 
    var links = document.querySelectorAll('div#mw-content-text table.wikitable tbody tr td i b a'); 
    return Array.prototype.map.call(links, function(e) { 
     return 'https://en.wikipedia.org' + e.getAttribute('href'); 
    }); 
} 

casper.start('https://en.wikipedia.org/wiki/David_Bowie_discography'); 

casper.then(function() { 
    // aggregate results for the 'casperjs' search 
    links = this.evaluate(getLinks); 

    casper.each(links, function (self, link) { 
     self.thenOpen(link, function() { 
      this.echo(this.getTitle() + " - " + link); 
     }); 
    }); 
}); 


casper.run();