CasperJS thenOpen()执行两次

时间:2016-02-04 20:37:17

标签: javascript casperjs

我正在构建一个简单的Web scraper。我正在尝试使用此网址中的班级名称.pro-title抓取每个链接 - http://www.home.com/professionals/c/oho,-TN。我不明白为什么thenOpen()函数正在执行两次。

var casper = require('casper').create({
    logLevel:"verbose",
    debug:true
});

var links;
var name;
var paragraph;
var firstName;

casper.start('http://www.home.com/professionals/c/oho,-TN');

casper.then(function getLinks(){
     links = this.evaluate(function(){
        var links = document.getElementsByClassName('pro-title');
        links = Array.prototype.map.call(links,function(link){
            return link.getAttribute('href');
            //this.echo(links);
        });
        return links;
    });
});
casper.then(function(){
    this.each(links,function(self,link){
        self.thenOpen(link,function(a){
            //this.echo(this.getCurrentUrl());
            // this.echo(this.getCurrentUrl());
            //this.echo("first");
            var firstName = this.fetchText('div.info-list-text');
            this.echo(firstName);
        });
    });
});
casper.run(function(){
    this.exit();
});

1 个答案:

答案 0 :(得分:1)

Artjom B是正确的,因为您收集的href属性不是有效的网址。您可以使用正则表达式消除它们。

var casper = require('casper').create({
    logLevel:"verbose",
    debug:true
});

var links;
var name;
var paragraph;
var firstName;
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);

casper.start('http://www.houzz.com/professionals/c/Nashville,-TN');

casper.then(function getLinks(){
     links = this.evaluate(function(){
        var links = document.getElementsByClassName('pro-title');
        links = Array.prototype.map.call(links,function(link){
            return link.getAttribute('href');
        });
        return links;
    });
});
casper.then(function(){
    this.each(links,function(self,link){
      if (link.match(regex)) {
        self.thenOpen(link,function(a){
          var firstName = this.fetchText('div.info-list-text');
          this.echo(firstName);
        });
      }
    });
});
casper.run(function(){
    this.exit();
});