无法在 PhantomJS 脚本中加载 `cheerio`
Cannot load `cheerio` in PhantomJS script
我在 Mac(自制软件安装)上使用节点版本 4.8.1,PhantomJS 版本 2.1.1 和 cheerio@0.22.0
现在,如果我像这样在 phantomjs 脚本中需要 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 与它一起使用。
有没有办法让 cheerio 在 PhantomJS 中工作?或者可以替代 cheerio 的方法?
cheerio 是一个 node.js 模块,但 PhantomJS 不是 node.js。由于 cheerio 是 "jQuery for server",您实际上可以将真实的 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');
}))
}
);
我在 Mac(自制软件安装)上使用节点版本 4.8.1,PhantomJS 版本 2.1.1 和 cheerio@0.22.0
现在,如果我像这样在 phantomjs 脚本中需要 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 与它一起使用。
有没有办法让 cheerio 在 PhantomJS 中工作?或者可以替代 cheerio 的方法?
cheerio 是一个 node.js 模块,但 PhantomJS 不是 node.js。由于 cheerio 是 "jQuery for server",您实际上可以将真实的 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');
}))
}
);