无法在PhantomJS脚本中加载`cheerio`

时间:2017-03-24 21:38:43

标签: node.js phantomjs cheerio

我在Mac上使用节点版本4.8.1(自制安装),PhantomJS版本2.1.1和cheerio@0.22.0

现在如果我在像这样的幻像脚本中需要cheerio

// myscript.js
var cheerio = require('cheerio');
console.log("done");

并使用

运行该脚本(其中没有其他内容)
$ phantomjs myscript.js

然后我会收到此错误:

TypeError: Object is not a constructor 
(evaluating 'require("inherits")(Parser, require("events").EventEmitter)')

phantomjs://platform/Parser.js:124

我可以用PhantomJS做各种各样的事情。我唯一能做的就是使用cheerio。

我有办法让PhantomJS内的cheerio工作吗?或者替代cheerio会起作用吗?

1 个答案:

答案 0 :(得分:1)

cheerio是一个node.js模块,但PhantomJS不是node.js.由于cheerio是“服务器的jQuery”,你实际上可以使用真正的jQuery与Phantom,包括它到你的目标页面:
http://phantomjs.org/api/webpage/method/include-js.html

page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', 
function() {
(page.evaluate(function() {
  // jQuery is loaded, now manipulate the DOM
  var $loginForm = $('form#login');
      $loginForm.find('input[name="username"]').value('phantomjs');
      $loginForm.find('input[name="password"]').value('c45p3r');
    }))
  }
);