CasperJS 找不到 jQuery

CasperJS doesn't find jQuery

我正在使用 jQuery 选择器进行 casper.js 抓取。我明白有必要 place the jQuery calls inside casper.evaluate().

问题是在下面这三个函数的last中,引发了一个ReferenceError: Can't find variable: $。前两个绝对没问题。

// On main page, scrape links to sub-pages.
function getLinks() {
    var links = $('li.ds-artifact-item a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

// On main page, scrape sub-pages' titles.
function getTitles() {
    var titles = $('li.ds-artifact-item a');
    return Array.prototype.map.call(titles, function(e) {
        return e.innerHTML;
    });
}

// On sub-page, scrape document description.
function getDescription(){
    var descriptions = $('td.label-cell:contains(date)');
    return Array.prototype.map.call(descriptions, function(e) {
        return e.innerHTML;
    });
}

这是脚本的其余部分,隐藏了不重要的细节。请注意,anotherValidPage 是有效的 URL,其中 returns HTTP 200(成功)。

var links = []; var titles = []; var descriptions = [];

casper.start(validPage, function() {
    links = this.evaluate(getLinks);
    titles = this.evaluate(getTitles);
});


casper.then(function() {
    // echo results
    this.echo(links.length + ' links found:');
    this.echo(' - ' + links.join('\n - '));
    this.echo(titles.length + ' titles found:');
    this.echo(' - ' + titles.join('\n - '));
    });

casper.thenOpen(anotherValidPage, function(){});

casper.then(function(){
    // This call is the problematic one.
    descriptions = this.evaluate(getDescription());

    this.echo(descriptions.length + ' descriptions found:');
    this.echo(' - ' + descriptions.join('\n - '));
});

casper.run();

我找到了解决方案:我不得不调用 this.evaluate(getDescription) 而不是调用 this.evaluate(getDescription()),因为我想我是在执行函数而不是将其作为参数传递,糟糕。