我已经npm install node-phantom
安装了node-phantom,但是当我运行此代码时,它会给Cannot find module 'webpage'
此错误
var webpage = require('webpage').create(),
url = "https://www.example.com/cba/abc",
hrefs = new Array();
webpage.open(url,function(status){
if(status=="success"){
var results = page.evaluate(function(){
$("#endpoints").each(function() {
hrefs.push($(this).attr("href"));
});
return hrefs;
});
console.log(JSON.stringify(results));
phantom.exit();
}
});
答案 0 :(得分:1)
您不需要节点幻像中的网页模块。您可以使用其API来获取网页模块的表示。它必须以这种方式完成,因为PhantomJS与node.js具有不同的执行运行时。他们通常不能使用相同的模块。这就是为什么在node-phantom和phantom这两个执行环境之间存在桥梁的原因。它们基本上复制了PhantomJS的API,以便在node.js中使用。
根据文档,您不需要网页,而是获得一个页面:
var phantom = require('node-phantom');
phantom.create(function(err,ph) {
return ph.createPage(function(err,page) {
// do something with page: basically your script
});
});
您无法复制和粘贴现有的PhantomJS代码。存在差异,因此您将不得不研究API(基本上是github上的README)。
完整的代码翻译:
var phantom = require('node-phantom');
phantom.create(function(err,ph) {
return ph.createPage(function(err,page) {
page.open(url,function(status){
if(status=="success"){
page.evaluate(function(){
hrefs = [];
$("#endpoints").each(function() {
hrefs.push($(this).attr("href"));
});
return hrefs;
}, function(err, results){
console.log(JSON.stringify(results));
ph.exit();
});
}
});
});
});
page.evaluate
仍然是沙箱,因此您无法像hrefs
一样使用外部变量。