CasperJS评估函数第二次不工作



我对casperjs&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();

这很有效。函数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();

最新更新