【发布时间】:2013-03-22 15:25:17
【问题描述】:
我想在我的 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 编写与上面第一个 sn-p 代码等效的代码(通过阅读咖啡脚本 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 上,什么都没有发生.. 没有任何返回,过程也没有停止.. 有什么想法吗?
更新:
我刚刚在phantomjsfaq读到这个:
问:为什么 PhantomJS 不写成 Node.js 模块?
答:简短的回答:“没有人可以侍奉两个主人。”
更详细的解释如下。
到目前为止,这样做在技术上非常具有挑战性。
每个 Node.js 模块本质上都是 Node.js 核心的“奴隶”, 即“主人”。在当前状态下,PhantomJS(及其包含 WebKit)需要完全控制(以同步方式) 一切:事件循环、网络堆栈和 JavaScript 执行。
如果意图只是直接从脚本中使用 PhantomJS 在 Node.js 中运行,这样的“松散绑定”可以通过 启动 PhantomJS 进程并与之交互。
嗯..这可能与它有关吗?但是那样整个库就没有意义了!
更新 2:
我在web 中发现了这个代码,它做同样的事情:
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();
});
});
});
});
不幸的是,这也不起作用..结果相同!
【问题讨论】:
-
因为你不明白它是如何工作的和/或你不能让它在你的情况下工作而称它为“愚蠢”是很粗鲁的。
-
另外,github.com/sheebz/phantom-proxy 比其他 Node.js 桥更推荐。人们一直在使用 PhantomJS 与 Ruby、PHP、Node.js 进行桥接,并取得了不同程度的成功。
-
我为我的措辞强硬表示歉意,我会从问题中删除它。我还会看看
phantom-proxy.. 在一天结束时,我的目标是把事情做好,不是贬低别人的努力。 -
这是过时的,应该被编辑或删除。它不反映最新的 phantomjs-node 包及其功能。
标签: javascript jquery node.js coffeescript phantomjs