PhantomJS / CasperJS - 保持会话无限期打开并通过HTTP与之交互?

时间:2014-03-27 00:34:43

标签: javascript phantomjs casperjs

我想要一个启动页面的CasperJS脚本,然后无限期地保持打开状态,这样我就可以随时通过HTTP向它发送命令。问题是整个CasperJS进程在casper.run调用完成后立即关闭。我已尝试通过在步骤中使用长wait次调用来解决此问题,但随后Web服务器无法对Casper执行任何操作,因为Casper正忙着等待wait调用完成。< / p>

var port = 6100;

var casper = require("casper").create();
casper.start("http://google.com");
casper.then(function() {
  // If I include this wait, then the server works, but the
  // `this.capture` call inside it never executes, presumably
  // because casper is executing the `then` calls in serial.
  // But if I don't include this wait, the entire process finishes
  // instantly and I can't use the server anyway.
  this.wait(100000000, function() {
    console.log("i have waited");
  });
});
casper.run(function() {
  console.log("finished");
});

var pictureNum = 0;
require("webserver").create().listen(port, function(request, response) {
  var src = "my_picture_" + (pictureNum++) + ".png";
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.write("written " + src);
  response.close();

  casper.then(function() {
    // How can I do this whenever I want?
    this.capture(src);
  });
  casper.run(); // Maybe?
});
console.log("listening on port", port);

有什么方法可以让Casper保持打开并像这样发送命令吗?

编辑:事实证明,我可以很容易地使用原始PhantomJS做到这一点,只是不要调用exit。这非常适合作为PhantomJS脚本:

var port = 6100;

var page = require("webpage").create();
page.open("http://google.com", function() { });

var pictureNum = 0;
require("webserver").create().listen(port, function(request, response) {
  var src = "my_picture_" + (pictureNum++) + ".png";
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.write("written " + src);
  response.close();
  page.render(src);
});
console.log("listening on port", port);

但我的问题仍然是如何在利用CasperJS的优点的同时做同样的事情。

1 个答案:

答案 0 :(得分:13)

终于得到了合理的东西!

默认情况下,有一个onRunComplete设置会调用this.exit。如果使用不执行任何操作的函数覆盖它,则在run完成时,该过程不会终止。然后,您可以再次致电thenrun,这些任务就可以正常运行。完整的例子:

var port = 6100;

var casper = require("casper").create({
  onRunComplete: function() {
    // Don't exit on complete.
  }
});
casper.start("http://google.com");
casper.run(function() {
  console.log("finished");
});

var pictureNum = 0;
require("webserver").create().listen(port, function(request, response) {
  var src = "my_picture_" + (pictureNum++) + ".png";
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.write("written " + src);
  response.close();

  // HACK: without this, the `run()` call will re-execute all
  // the previous steps too!
  casper.steps = [];
  casper.step = 0;

  casper.then(function() {
    this.capture(src);
  });
  casper.run();
});
console.log("listening on port", port);