如何将PhantomJS作为服务器运行并远程调用? [英] How to run PhantomJS as a server and call it remotely?

查看:137
本文介绍了如何将PhantomJS作为服务器运行并远程调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is probably a very basic question. I would like to run a headless browser PhantomJS as a server but not as a command line tool.

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

Once it is running I would like to call it remotely over HTTP. The only thing I need is to send a URL and get back the HTML output. I need it to generate HTML for an AJAX application to make it searchable.

是否可能?

推荐答案

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

You can run PhantomJS perfectly fine as a webserver, because it has the Web Server Module. The examples folder contains for example a server.js example. This runs standalone without any dependencies (without node).

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-node ,它是节点的PhantomJS桥。

If you want to run PhantomJS through node.js then this is also easily doable using the phantomjs-node which is a PhantomJS bridge for node.

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);
  });
});



注释



你可以自由使用这个就像你没有多个同时请求一样。如果你这样做,那么你需要同步请求(因为只有一个页面对象)或者你需要创建一个新的页面对象,完成后再次 close()

Notes

You can freely use this as is as long you don't have multiple requests at the same time. If you do, then you either need to synchronize the requests (because there is only one page object) or you need to create a new page object on every request and close() it again when you're done.

这篇关于如何将PhantomJS作为服务器运行并远程调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆