如何运行PhantomJS作为服务器并远程调用它?

这可能是一个非常基本的问题。 我想运行一个无头浏览器PhantomJS作为服务器,但不作为命令行工具。

一旦运行,我想通过HTTP远程调用它。 我唯一需要的是发送一个URL并取回HTML输出。 我需要它为AJAX应用程序生成HTML以使其可search。

可能吗 ?

您可以完美地运行PhantomJS作为Web服务器,因为它具有Web服务器模块 。 示例文件夹包含例如server.js示例 。 这运行独立,没有任何依赖(没有节点)。

 var page = require('webpage').create(), server = require('webserver').create(); var service = server.listen(port, function (request, response) { console.log('Request received at ' + new Date()); // TODO: parse `request` and determine where to go page.open(someUrl, function (status) { if (status !== 'success') { console.log('Unable to post!'); } else { response.statusCode = 200; response.headers = { 'Cache': 'no-cache', 'Content-Type': 'text/plain;charset=utf-8' }; // TODO: do something on the page and generate `result` response.write(result); response.close(); } }); }); 

如果您想通过node.js运行PhantomJS,那么使用PhantomJS 节点(这是PhantomJS桥节点)也很容易实现。

 var http = require('http'); var phantom = require('phantom'); phantom.create(function (ph) { ph.createPage(function (page) { http.createServer(function (req, res) { // TODO: parse `request` and determine where to go page.open(someURL, function (status) { res.writeHead(200, {'Content-Type': 'text/plain'}); // TODO: do something on the page and generate `result` res.end(result); }); }).listen(8080); }); }); 

笔记

只要你没有同时有多个请求,你可以自由使用它。 如果这样做,则需要同步请求(因为只有一个page对象),或者需要在每个请求上创build一个新page对象,并在完成后再次close()

最简单的方法是制作一个python脚本或简单的东西来启动服务器,并使用python websockets与它进行通信,使用Websorting的forms来查询网站并获取页面源代码。 任何自动化都可以通过cron作业完成,或者如果您在Windows上,可以使用Tasksfunction来自动启动python脚本。