CasperJS第二次评估功能不起作用

时间:2013-12-03 06:59:48

标签: javascript casperjs

我对casperjs& amp; JavaScript,并一直在尝试测试我们的新网站。在浏览了casperjs文档并编写了一些示例程序后,我对evaluate()函数有了一些了解。但现在我陷入了一个奇怪的问题。我使用evaluate函数来查找网页内的所有链接。现在我想尝试所有这些链接并从中获取一些信息。现在我的问题是我第二次使用evaluate()函数时它会被跳过。这是完全出乎意料的行为。请填写我遗漏的内容。我附上了这个用于重现问题的示例代码。

var BASE_URL = "http://www.google.com";
var links = [];
var divs = [];
var casper = require('casper').create({verbose: true,});

function getLinks() {
    var links = document.querySelectorAll('h3.r a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

function getDivs(){
        __util__.echo("get Divs Function");
        var divs = document.getElementsByTagName('div');
        return Array.prototype.map.call(divs, function(e) {
        return e;
    });
}

casper.start(BASE_URL, function() {
    this.fill('form[action="/search"]', { q: 'casperjs' }, true);
});

casper.then(function() {
    links = this.evaluate(getLinks);
    this.echo("links == " + links);
});

casper.waitForUrl(BASE_URL, function(){
    this.echo(this.getCurrentUrl());
}, function(){}, 20000);

casper.then(function() {
    this.echo("------------------")
    divs = this.evaluate(getDivs);
    this.echo("^^^^^^^^^^^^^^^^^^")
    this.echo("divs == " + divs);
});

casper.run();

1 个答案:

答案 0 :(得分:2)

这很有效。你在函数getDivs __utils__上缺少's'。

var BASE_URL = "http://www.google.com";
var links = [];
var divs = [];
var casper = require('casper').create({verbose: true,});

function getLinks() {
    var links = document.querySelectorAll('h3.r a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

function getDivs(){
    __utils__.echo("get Divs Function");
    var divs = document.getElementsByTagName("div");
    return Array.prototype.map.call(divs, function(e) {
        return e;
    });
}

casper.start(BASE_URL, function() {
    this.fill('form[action="/search"]', { q: 'casperjs' }, true);
});

casper.then(function() {
    links = this.evaluate(getLinks);
    this.echo("links == " + links);
});

casper.waitForUrl(BASE_URL, function(){
    this.echo(this.getCurrentUrl());
}, function(){}, 20000);

casper.then(function() {
    this.echo("------------------");
    divs = this.evaluate(getDivs);
    this.echo("^^^^^^^^^^^^^^^^^^");
    this.echo(JSON.stringify(divs));
});

casper.run();