【问题标题】:communication between Node/Express and Spooky/Casper jsNode/Express 和 Spooky/Casper js 之间的通信
【发布时间】:2014-05-20 19:58:51
【问题描述】:

我尝试将 node/express 与诡异的 js 结合起来。但是,我无法发回使用 spookyjs 检索到的元素。下面是我的代码。使用我的代码,我只打印了 foo,尽管我打算用 spooky 来获取所有 DOM 元素数据。我想知道是否有人有经验如何做到这一点?提前致谢!

server.js

var express = require("express"); 
var site = express.createServer(); 
var fill = require('./spooky_fill.js');

site.use(express.static(__dirname + '/..'));

site.get("/", function(req, res) {   
fs.createReadStream("./index.html").pipe(res); });

site.get('/fill', fill.search);

site.listen(9201);

console.log("Server listening on http://localhost:9201");

spooky_fill.js

try {
  var Spooky = require('spooky');
} catch(e) {
  var Spooky = require('../lib/spooky');
}

exports.search = function(req, res) {

  var spooky = new Spooky({
    child: {
      transport: 'http'
    },
    casper: {
      logLevel: 'debug',
      verbose: true
    }
  }, function(err) {
    if(err) {
      e = new Error('Failed to initialize SpookyJS');
      e.details = err;
      throw e;
    }

    var js;
    spooky.start('https://www.google.com');
    spooky.then(function() {
      js = this.evaluate(function() {
        return document;
      });

    });
    res.write(js); //nothing is printed out from here

    res.write("foo"); //this is printed out

    spooky.then(function() {
      this.emit('clog', 'finished');
    });

    spooky.run();
  });

  spooky.on('error', function(e, stack) {
    console.error(e);

    if(stack) {
      console.log(stack);
    }
  });

  /*
   // Uncomment this block to see all of the things Casper has to say.
   // There are a lot.
   // He has opinions.
   spooky.on('console', function (line) {
   console.log(line);
   });
   */

  spooky.on('clog', function(message) {
    console.log(message);
  });

  spooky.on('log', function(log) {
    if(log.space === 'remote') {
      console.log(log.message.replace(/ \- .*/, ''));
    }
  });
};

【问题讨论】:

  • 两件事:js 是在诡异的上下文中定义的,但你想在 casper 上下文中设置它(then 块)。这行不通。其次,您不能从页面上下文返回document。只能传递基本类型:int、string、[]、{}。
  • This spookyjs issue 描述了如何通过数组表示法中的then 将值从 spooky 传递给 casper,然后通过 spooky.emitspooky.on 传回。

标签: node.js express casperjs spookyjs


【解决方案1】:

我通过执行以下操作解决了这个问题:

spooky.then(function() {
    this.emit('page.loaded', this.getHTML('html', true));
});

spooky.on('page.loaded', function (html) {
    console.log('###############EMIT');
    res.send(html);
});

【讨论】:

  • 您应该描述您的代码,然后接受答案。
  • @ArtjomB。谢谢,所以基本上 spooky 可以收听您发出的消息,我们可以在那里使用 res.send() 将我们的消息发送回 espress 服务器
  • 这对我很有用。我很难将计数器变量返回到节点以使用 socket.io 作为进度条。谢谢
猜你喜欢
  • 2014-07-29
  • 2021-09-15
  • 2012-09-22
  • 2020-12-12
  • 2017-05-02
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多