我正在尝试使用用于解析页面和提取相关链接的 CasperJS 编写蜘蛛。有问题的站点具有文件和文件夹的分层视图。我已经编写了一个递归方法来执行文件结构的导航,但是在该方法的第一次迭代之后,我的数组返回 null,即使函数运行正确。任何确定问题的帮助将不胜感激。
var processPage = function() {
//Gather links
var links = this.evaluate(function() { //links is the array being set to null
var elements = document.querySelectorAll("a");
return Array.prototype.map.call(elements, function(e) {
//check link matches our white list
var matchesWhitelist = false;
var fileDescription = e.querySelector("span").innerHTML;
console.log("span text:" + fileDescription);
//begin checking
if (fileDescription.indexOf('.mp3') != -1) matchesWhitelist = true;
//if (fileDescription.indexOf('.wmv') != -1) .... etc
//failing that is the link for a folder rather than a file
var hrefLink = e.getAttribute("href");
if (hrefLink.indexOf('folder-files') != -1) matchesWhitelist = true;
if (matchesWhitelist) {
console.log('match');
console.log('Adding link: ' + hrefLink)
return hrefLink;
}
else {
console.log('no match');
}
});
});
console.log("linkslength: " + links.length); // links will be null upon recursion
for (var i = 0; i < links.length; i++) {
//check link matches our 'whitelist'
this.thenOpen("https://TLD" + links[i]).then(function() {
this.echo("New URL: " + this.getCurrentUrl());
//check for files
if (this.exists(".fileDownload")) {
//extract link
} else {
//assume that this is a 'folder' link and send to be processed for more links
casper.then(processPage); //continue recursion
};
});
}
谢谢