1

所以我有一些代码,我想在外面传递一个变量,这样我就可以评估另一个页面并注入前一页的代码。

我不是这里的专家,我只是没有掌握这个概念。谁能帮我理解我做错了什么?

var scheduleArray = [];

//blah blah removed code...everything works up to this point

casper.thenEvaluate(function(scheduleArray){

    console.log("##Your schedule is " + document.querySelector('form + div table').textContent );
    var rawSchedule = document.querySelector('form + div table').textContent;
    scheduleArray = rawSchedule.match(/((Monday)|(Tuesday)|(Wednesday)|(Thursday)|(Friday)|(Saturday)|(Sunday))([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4})((5)|(C6)|(6)|(7H)|(7F)|(715)|(8F)|(10F)|(12F)|(1F)|(2H)|(C2)|(2))/gi);
    console.log("##scheduleArray");
    console.log(scheduleArray);

    for (i=0;i<scheduleArray.length;i++){
        console.log(scheduleArray[i]);
    }


},scheduleArray);

casper.then(function(scheduleArray){
    console.log("##scheduleArray");
//This loop contains no data
    for (i=0;i<scheduleArray.length;i++){
            console.log(scheduleArray[i]);
        }
},scheduleArray);
4

1 回答 1

0

我为您编写了一个小示例代码来说明如何在评估和 casper 脚本之间传递结果:

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

var array = []

casper.start('http://www.ecma-international.org/memento/TC39.htm');

casper.then(function() {
    array = casper.evaluate(function () {
        var nodes = document.querySelectorAll('a')
        var result = Array.prototype.map.call(nodes, function (div) {
            return div.href
        })
        return result
    });
});

casper.then(function () {
    casper.echo(array.length);
    casper.echo(array.join("\n"))
})

casper.run()

输出:

22
http://www.ecma-international.org/default.htm
http://www.ecma-international.org/contact/contact.html
http://www.ecma-international.org/sitemap/ecma_sitemap.html
http://www.ecma-international.org/memento/index.html
http://www.ecma-international.org/activities/index.html
http://www.ecma-international.org/news/index.html
http://www.ecma-international.org/publications/index.html
http://www.ecma-international.org/memento/history.htm
... ignore some lines

所以,来到你的代码:

  1. 参数的更改evaluate不会对您的全局变量进行更改。也就是说,无论你对scheduleArrayinside做什么evaluate,全局变量scheduleArray都是一样的。

  2. 在内部evaluate,您应该使用console.log来记录,但在外部evaluate,您应该使用casper.echo.

于 2016-07-10T17:07:10.010 回答