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

How to run PhantomJS as a server and call it remotely?

本文关键字:程调用 调用 运行 PhantomJS 服务器      更新时间:2023-09-26

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

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

你可以很好地运行PhantomJS作为一个Web服务器,因为它有Web服务器模块。例如,examples文件夹包含一个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 -node,这是一个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);
  });
});
指出

你可以自由地使用这个,只要你没有在同一时间有多个请求。如果您这样做,那么您要么需要同步请求(因为只有一个page对象),要么需要在每个请求上创建一个新的page对象,并在完成后再次创建close()

最简单的方法是编写一个python脚本或一些简单的东西来启动服务器并使用python websockets与之通信,使用web形式的各种查询网站并获得页面源。任何自动化都可以通过cron作业完成,或者如果您在Windows上,您可以使用Tasks功能来自动启动python脚本。