我想在我的node.js脚本中使用phantomjs。有一个phantomjs-node库..但不幸的是作者用这种奇怪的咖啡脚本代码来解释他在做什么:
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
page.open "http://www.google.com", (status) ->
console.log "opened google? ", status
page.evaluate (-> document.title), (result) ->
console.log 'Page title is ' + result
ph.exit()
现在,如果我直接使用JavaScript来操作phantomjs,代码应该是这样的this:
var page = require('webpage').create();
page.open(url, function (status) {
var title = page.evaluate(function () {
return document.title;
});
console.log('Page title is ' + title);
});
基本上,我正在尝试用普通JavaScript编写上面第一个代码片段的等效代码(通过阅读CoffeeScript documentation.. 这是我所做的:
// file name: phantomTest.js
var phantom = require('phantom');
phantom.create(function(ph) {
ph.createPage(function(page) {
page.open('http://www.google.com', function(status) {
console.log('opened google?', status);
var title = page.evaluate(function() {
return document.title;
});
console.log('page title is ' + title);
});
});
ph.exit();
});
不幸的是它没有工作!如果我运行
node phantomTest.js
在shell上,什么也没有发生...没有返回值,进程也不会停止...有什么想法吗?
更新:
我刚刚在phantomjs faq中读到了这个:
问:为什么PhantomJS没有写成Node.js模块?
答:简短的答案是:“一个人不能同时服务于两个主人。”
更长的解释如下。
目前,这样做在技术上非常具有挑战性。
每个Node.js模块本质上都是“从属于”Node.js核心的“主人”。在当前状态下,PhantomJS(及其包含的WebKit)需要对所有事情(事件循环、网络堆栈和JavaScript执行)进行完全控制(以同步方式)。
如果打算从Node.js中运行的脚本中直接使用PhantomJS,可以通过启动PhantomJS进程并与之交互来实现这种“松散绑定”。
嗯...这可能与此有关吗?但那整个库就没有意义了!
更新2:
我在网站上找到了一段相同效果的代码:
var phantom = require('phantom');
phantom.create(function(ph) {
return ph.createPage(function(page) {
return page.open("http://www.google.com", function(status) {
console.log("opened google? ", status);
return page.evaluate((function() {
return document.title;
}), function(result) {
console.log('Page title is ' + result);
return ph.exit();
});
});
});
});
很遗憾,这也不起作用...结果相同!