JavaScript/CasperJS 循环页面时的超时处理

JavaScript/CasperJS handling of timeouts when looping over pages

我对这个脚本有疑问。它应该加载保存在 prova.txt 中的一些链接(逐行),然后将链接一个一个地传递给 CasperJS 并获取页面的 html。我知道 timeouts/JavaScript.

一定有问题

这是脚本:

var fs = require('fs');
var file_h = fs.open('prova.txt', 'r');
var line = file_h.readLine();
var links = new Array();
var casper = require('casper').create();

while(line) {
    line = file_h.readLine();
    links.push(line);
}

(function theLoop (i) {
    console.log("LOOP");
    casper.start(links[i], function() {
        setTimeout(function () {
            fs.write("stats" + i + ".html", this.getHTML() );
            i = i + 1;
            if (--i) {
                theLoop(i);
            }
        }, 2000);
    });
    casper.run();
})(4);

我使用的文档:http://scottiestech.info/2014/07/01/javascript-fun-looping-with-a-delay/

不要在同一个 casper 实例上多次调用 startrun

casper.start();

(function theLoop (i) {
    console.log("LOOP");
    casper.thenOpen(links[i], function() {
        this.wait(2000, function () {
            fs.write("stats" + i + ".html", this.getHTML() );
            if (--i) {
                theLoop(i);
            }
        });
    });
})(4);

casper.run();

此外,您似乎想将 i 减少到 0,因此您不应在下一行递增 (i = i + 1) 并递减 --i

请记住,如果您在 CasperJS 脚本中使用 setTimeout,您将中断步进控制流并且必须以某种方式捕获中断的执行。使用 CasperJS 的功能,直到它变得不可避免。例如,我将 setTimeout(function(){}, x) 替换为 casper.wait(x, function(){})