如何在casperjs中循环

jpm*_*ris 5 javascript phantomjs casperjs

我试图点击"下一个"按钮N次并每次抓取页面源.我知道我可以在远程网站上运行任意函数,所以我只使用远程函数nextPage()而不是click()我如何运行以下任意次:

var casper = require('casper').create();

casper.start('http://www.example.com', function() {

    this.echo(this.getHTML());
    this.echo('-------------------------');

    var numTimes = 4, count = 2;

    casper.repeat(numTimes, function() {
        this.thenEvaluate(function() {
            nextPage(++count);
        });

        this.then(function() {
            this.echo(this.getHTML());
            this.echo('-------------------------');
        });
    });

});
Run Code Online (Sandbox Code Playgroud)

'我'这是我试图在javascript for循环中使用的索引.

所以tl; dr:我想舔'下一个',打印页面来源,点击'下一步',打印页面来源,点击'下一步'...继续N次.

sud*_*pto 7

首先,您可以将值传递给远程页面上下文(即以thenEvaluate这样的方式运行:

    this.thenEvaluate(function(remoteCount) {
        nextPage(remoteCount);
    }, ++count);
Run Code Online (Sandbox Code Playgroud)

但是,Casper#repeat在这里使用可能不是一个好的函数,因为循环不会等待每个页面加载然后捕获内容.

您可能更愿意设计基于事件的链接.

代码的工作流程将是:

  1. 有一个全局变量(或至少是下面提到的函数可访问的变量)来存储countlimit.

  2. 听取load.finished事件并在此处获取HTML,然后调用下一页.

简化的代码可以是:

var casper = require('casper').create();

var limit = 5, count = 1;

casper.on('load.finished', function (status) {
    if (status !== 'success') {
        this.echo ("Failed to load page.");
    }
    else {
        this.echo(this.getHTML());
        this.echo('-------------------------');
    }



    if(++count > limit) {
        this.echo ("Finished!");

    }
    else {
        this.evaluate(function(remoteCount) {
            nextPage(remoteCount);
            // [Edit the line below was added later]
            console.log(remoteCount);
            return remoteCount;
        }, count);

    }

});

casper.start('http://www.example.com').run();
Run Code Online (Sandbox Code Playgroud)

注意:如果您使用高负载的JS进程页面等,您可能还想wait在调用nextPage之前添加一个:

this.wait( 
   1000, // in ms
   function () {
        this.evaluate(function(remoteCount) {
            nextPage(remoteCount);
        }, count);
   }
);     
Run Code Online (Sandbox Code Playgroud)

[编辑添加]以下事件监听器将帮助您进行调试.

// help is tracing page's console.log 
casper.on('remote.message', function(msg) { 
    console.log('[Remote Page] ' + msg); 
}); 

// Print out all the error messages from the web page 
casper.on("page.error", function(msg, trace) { 
    casper.echo("[Remote Page Error] " + msg, "ERROR"); 
    casper.echo("[Remote Error trace] " + JSON.stringify(trace, undefined, 4)); 
});
Run Code Online (Sandbox Code Playgroud)