casperjs评估功能不起作用

时间:2015-07-20 08:59:18

标签: casperjs

我正在研究casperjs。我编写以下程序来获取输出:

var casper = require('casper').create();
var cookie;
casper.start('http://wordpress.org/');
casper.then(function() {
       this.evaluate(function() {
            cookie=document.cookie;
       })
   })

casper.then(function() {
console.log("Page cookie");
console.log(cookie);
})
casper.run(function() {
 this.echo('Done.').exit();
})

以上输出为:
  页面饼干
 未定义
 完成。

为什么它给我未定义?帮帮我吧。

2 个答案:

答案 0 :(得分:1)

评估背后的概念是,您将代码传递给浏览器的控制台并在那里执行您的代码。如果在evaluate方法中定义任何变量,那么变量将是该方法的本地变量。该范围是本地的。当您与Casper打交道时,您应该考虑变量的范围 所以,当你试图打印出来时," cookie"在主要功能中它会说它是未定义的。这是预期的。
请注意,您无法在evaluate方法中使用echo(),console.log()。

  

cookie = this.evaluate(function() { var cookieLocal=document.cookie; return cookieLocal; })

这里" cookieLocal"是一个局部变量。 这将返回值为Gloabal变量" cookie"。因此,当您尝试在main函数中打印值时,它将按预期工作。我希望这会让你在声明变量时考虑范围。你可以直接返回做返回。无需使用局部变量。

  

cookie = this.evaluate(function() { return document.cookie; })

使用evaluate方法时,我建议的另一个重要事项。尝试在开发代码时使用Try catch方法。根据您的要求,它不会在生产中需要。我们无法在控制台内打印任何内容。所以使用try catch进行调试。

  

casper.then(function() { cookie = this.evaluate(function() { try { return document.cookie; } catch (e) { return e; } }) this.echo (JSON.stringify ('cookie :'+cookie)); })

请注意,this.echo()应该在评估方法之外 希望这将是一个有用的。

答案 1 :(得分:-2)

删除var cookie

        cookie = casper.evaluate(function() {
                 return document.cookie;
         })
        casper.then(function() { 
                console.log("Page cookie");    
                console.log(cookie);        
        })

上面的代码对我来说很好。

相关问题