利用NodeJS和PhantomJS抓取网站页面信息以及网站截图


Posted in NodeJs onNovember 18, 2013

利用PhantomJS做网页截图经济适用,但其API较少,做其他功能就比较吃力了。例如,其自带的Web Server Mongoose最高只能同时支持10个请求,指望他能独立成为一个服务是不怎么实际的。所以这里需要另一个语言来支撑服务,这里选用NodeJS来完成。

安装PhantomJS

首先,去PhantomJS官网下载对应平台的版本,或者下载源代码自行编译。然后将PhantomJS配置进环境变量,输入

$ phantomjs

如果有反应,那么就可以进行下一步了。

利用PhantomJS进行简单截图

var webpage = require('webpage') , page = webpage.create(); page.viewportSize = { width: 1024, height: 800 }; page.clipRect = { top: 0, left: 0, width: 1024, height: 800 }; page.settings = { javascriptEnabled: false, loadImages: true, userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/19.0' }; page.open('http://www.baidu.com', function (status) { var data; if (status === 'fail') { console.log('open page fail!'); } else { page.render('./snapshot/test.png'); } // release the memory page.close(); });

这里我们设置了窗口大小为1024 * 800:

page.viewportSize = { width: 1024, height: 800 };

截取从(0, 0)为起点的1024 * 800大小的图像:

page.clipRect = { top: 0, left: 0, width: 1024, height: 800 };

禁止Javascript,允许图片载入,并将userAgent改为"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/19.0":

page.settings = { javascriptEnabled: false, loadImages: true, userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/19.0'};

然后利用page.open打开页面,最后截图输出到./snapshot/test.png中:

page.render('./snapshot/test.png') ;

 

NodeJS与PhantomJS通讯

我们先来看看PhantomJS能做什么通讯。

命令行传参
例如:
phantomjs snapshot.js http://www.baidu.com
命令行传参只能在PhantomJS开启时进行传参,在运行过程中就无能为力了。
标准输出
标准输出能从PhantomJS向NodeJS输出数据,但却没法从NodeJS传数据给PhantomJS。
不过测试中,标准输出是这几种方式传输最快的,在大量数据传输中应当考虑。
 HTTP
PhantomJS向NodeJS服务发出HTTP请求,然后NodeJS返回相应的数据。
这种方式很简单,但是请求只能由PhantomJS发出。
Websocket
值得注意的是PhantomJS 1.9.0支持Websocket了,不过可惜是hixie-76 Websocket,不过毕竟还是提供了一种NodeJS主动向PhantomJS通讯的方案了。
测试中,我们发现PhantomJS连上本地的Websocket服务居然需要1秒左右,暂时不考虑这种方法吧。
phantomjs-node
phantomjs-node成功将PhantomJS作为NodeJS的一个模块来使用,但我们看看作者的原理解释:
I will answer that question with a question. How do you communicate with a process that doesn't support shared memory, sockets, FIFOs, or standard input?
Well, there's one thing PhantomJS does support, and that's opening webpages. In fact, it's really good at opening web pages. So we communicate with PhantomJS by spinning up an instance of ExpressJS, opening Phantom in a subprocess, and pointing it at a special webpage that turns socket.io messages into alert()calls. Those alert() calls are picked up by Phantom and there you go!
The communication itself happens via James Halliday's fantastic dnode library, which fortunately works well enough when combined with browserify to run straight out of PhantomJS's pidgin Javascript environment.
实际上phantomjs-node使用的也是HTTP或者Websocket来进行通讯,不过其依赖庞大,我们只想做一个简单的东西,暂时还是不考虑这个东东吧。

 

设计图

利用NodeJS和PhantomJS抓取网站页面信息以及网站截图

 

让我们开始吧
我们在第一版中选用HTTP进行实现。

首先利用cluster进行简单的进程守护(index.js):

module.exports = (function () {
  "use strict"
  var cluster = require('cluster')
    , fs = require('fs');
  if(!fs.existsSync('./snapshot')) {
    fs.mkdirSync('./snapshot');
  }
  if (cluster.isMaster) {
    cluster.fork();
    cluster.on('exit', function (worker) {
      console.log('Worker' + worker.id + ' died :(');
      process.nextTick(function () {
        cluster.fork();
      });
    })
  } else {
    require('./extract.js');
  }
})();

然后利用connect做我们的对外API(extract.js):

module.exports = (function () {
  "use strict"
  var connect = require('connect')
    , fs = require('fs')
    , spawn = require('child_process').spawn
    , jobMan = require('./lib/jobMan.js')
    , bridge = require('./lib/bridge.js')
    , pkg = JSON.parse(fs.readFileSync('./package.json'));
  var app = connect()
    .use(connect.logger('dev'))
    .use('/snapshot', connect.static(__dirname + '/snapshot', { maxAge: pkg.maxAge }))
    .use(connect.bodyParser())
    .use('/bridge', bridge)
    .use('/api', function (req, res, next) {
      if (req.method !== "POST" || !req.body.campaignId) return next();
      if (!req.body.urls || !req.body.urls.length) return jobMan.watch(req.body.campaignId, req, res, next);
      var campaignId = req.body.campaignId
        , imagesPath = './snapshot/' + campaignId + '/'
        , urls = []
        , url
        , imagePath;
      function _deal(id, url, imagePath) {
        // just push into urls list
        urls.push({
          id: id,
          url: url,
          imagePath: imagePath
        });
      }
      for (var i = req.body.urls.length; i--;) {
        url = req.body.urls[i];
        imagePath = imagesPath + i + '.png';
        _deal(i, url, imagePath);
      }
      jobMan.register(campaignId, urls, req, res, next);
      var snapshot = spawn('phantomjs', ['snapshot.js', campaignId]);
      snapshot.stdout.on('data', function (data) {
        console.log('stdout: ' + data);
      });
      snapshot.stderr.on('data', function (data) {
        console.log('stderr: ' + data);
      });
      snapshot.on('close', function (code) {
        console.log('snapshot exited with code ' + code);
      });
    })
    .use(connect.static(__dirname + '/html', { maxAge: pkg.maxAge }))
    .listen(pkg.port, function () { console.log('listen: ' + 'http://localhost:' + pkg.port); });
})();

这里我们引用了两个模块bridge和jobMan。

其中bridge是HTTP通讯桥梁,jobMan是工作管理器。我们通过campaignId来对应一个job,然后将job和response委托给jobMan管理。然后启动PhantomJS进行处理。

通讯桥梁负责接受或者返回job的相关信息,并交给jobMan(bridge.js):

module.exports = (function () {
  "use strict"
  var jobMan = require('./jobMan.js')
    , fs = require('fs')
    , pkg = JSON.parse(fs.readFileSync('./package.json'));
  return function (req, res, next) {
      if (req.headers.secret !== pkg.secret) return next();
      // Snapshot APP can post url information
      if (req.method === "POST") {
        var body = JSON.parse(JSON.stringify(req.body));
        jobMan.fire(body);
        res.end('');
      // Snapshot APP can get the urls should extract
      } else {
        var urls = jobMan.getUrls(req.url.match(/campaignId=([^&]*)(\s|&|$)/)[1]);
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.statuCode = 200;
        res.end(JSON.stringify({ urls: urls }));
      }
  };
})();

如果request method为POST,则我们认为PhantomJS正在给我们推送job的相关信息。而为GET时,则认为其要获取job的信息。

jobMan负责管理job,并发送目前得到的job信息通过response返回给client(jobMan.js):

module.exports = (function () {
  "use strict"
  var fs = require('fs')
    , fetch = require('./fetch.js')
    , _jobs = {};
  function _send(campaignId){
    var job = _jobs[campaignId];
    if (!job) return;
    if (job.waiting) {
      job.waiting = false;
      clearTimeout(job.timeout);
      var finished = (job.urlsNum === job.finishNum)
        , data = {
        campaignId: campaignId,
        urls: job.urls,
        finished: finished
      };
      job.urls = [];
      var res = job.res;
      if (finished) {
        _jobs[campaignId] = null;
        delete _jobs[campaignId]
      }
      res.writeHead(200, {'Content-Type': 'application/json'});
      res.statuCode = 200;
      res.end(JSON.stringify(data));
    }
  }
  function register(campaignId, urls, req, res, next) {
    _jobs[campaignId] = {
      urlsNum: urls.length,
      finishNum: 0,
      urls: [],
      cacheUrls: urls,
      res: null,
      waiting: false,
      timeout: null
    };
    watch(campaignId, req, res, next);
  }
  function watch(campaignId, req, res, next) {
    _jobs[campaignId].res = res;
    // 20s timeout
    _jobs[campaignId].timeout = setTimeout(function () {
      _send(campaignId);
    }, 20000);
  }
  function fire(opts) {
    var campaignId = opts.campaignId
      , job = _jobs[campaignId]
      , fetchObj = fetch(opts.html);
    if (job) {
      if (+opts.status && fetchObj.title) {
        job.urls.push({
          id: opts.id,
          url: opts.url,
          image: opts.image,
          title: fetchObj.title,
          description: fetchObj.description,
          status: +opts.status
        });
      } else {
        job.urls.push({
          id: opts.id,
          url: opts.url,
          status: +opts.status
        });
      }
      if (!job.waiting) {
        job.waiting = true;
        setTimeout(function () {
          _send(campaignId);
        }, 500);
      }
      job.finishNum ++;
    } else {
      console.log('job can not found!');
    }
  }
  function getUrls(campaignId) {
    var job = _jobs[campaignId];
    if (job) return job.cacheUrls;
  }
  return {
    register: register,
    watch: watch,
    fire: fire,
    getUrls: getUrls
  };
})();

这里我们用到fetch对html进行抓取其title和description,fetch实现比较简单(fetch.js):

module.exports = (function () {
  "use strict"
  return function (html) {
    if (!html) return { title: false, description: false };
    var title = html.match(/\<title\>(.*?)\<\/title\>/)
      , meta = html.match(/\<meta\s(.*?)\/?\>/g)
      , description;
    if (meta) {
      for (var i = meta.length; i--;) {
        if(meta[i].indexOf('name="description"') > -1 || meta[i].indexOf('name="Description"') > -1){
          description = meta[i].match(/content\=\"(.*?)\"/)[1];
        }
      }
    }
    (title && title[1] !== '') ? (title = title[1]) : (title = 'No Title');
    description || (description = 'No Description');
    return {
      title: title,
      description: description
    };
  };
})();

最后是PhantomJS运行的源代码,其启动后通过HTTP向bridge获取job信息,然后每完成job的其中一个url就通过HTTP返回给bridge(snapshot.js):

var webpage = require('webpage')
  , args = require('system').args
  , fs = require('fs')
  , campaignId = args[1]
  , pkg = JSON.parse(fs.read('./package.json'));
function snapshot(id, url, imagePath) {
  var page = webpage.create()
    , send
    , begin
    , save
    , end;
  page.viewportSize = { width: 1024, height: 800 };
  page.clipRect = { top: 0, left: 0, width: 1024, height: 800 };
  page.settings = {
    javascriptEnabled: false,
    loadImages: true,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) PhantomJS/1.9.0'
  };
  page.open(url, function (status) {
    var data;
    if (status === 'fail') {
      data = [
        'campaignId=',
        campaignId,
        '&url=',
        encodeURIComponent(url),
        '&id=',
        id,
        '&status=',
      ].join('');
      postPage.open('http://localhost:' + pkg.port + '/bridge', 'POST', data, function () {});
    } else { 
      page.render(imagePath);
      var html = page.content;
      // callback NodeJS
      data = [
        'campaignId=',
        campaignId,
        '&html=',
        encodeURIComponent(html),
        '&url=',
        encodeURIComponent(url),
        '&image=',
        encodeURIComponent(imagePath),
        '&id=',
        id,
        '&status=',
      ].join('');
      postMan.post(data);
    }
    // release the memory
    page.close();
  });
}
var postMan = {
  postPage: null,
  posting: false,
  datas: [],
  len: 0,
  currentNum: 0,
  init: function (snapshot) {
    var postPage = webpage.create();
    postPage.customHeaders = {
      'secret': pkg.secret
    };
    postPage.open('http://localhost:' + pkg.port + '/bridge?campaignId=' + campaignId, function () {
      var urls = JSON.parse(postPage.plainText).urls
        , url;
      this.len = urls.length;
      if (this.len) {
        for (var i = this.len; i--;) {
          url = urls[i];
          snapshot(url.id, url.url, url.imagePath);
        }
      }
    });
    this.postPage = postPage;
  },
  post: function (data) {
    this.datas.push(data);
    if (!this.posting) {
      this.posting = true;
      this.fire();
    }
  },
  fire: function () {
    if (this.datas.length) {
      var data = this.datas.shift()
        , that = this;
      this.postPage.open('http://localhost:' + pkg.port + '/bridge', 'POST', data, function () {
        that.fire();
        // kill child process
        setTimeout(function () {
          if (++this.currentNum === this.len) {
            that.postPage.close();
            phantom.exit();
          }
        }, 500);
      });
    } else {
      this.posting = false;
    }
  }
};
postMan.init(snapshot);
效果

利用NodeJS和PhantomJS抓取网站页面信息以及网站截图

 

NodeJs 相关文章推荐
基于 Docker 开发 NodeJS 应用
Jul 30 NodeJs
基于NodeJS的前后端分离的思考与实践(三)轻量级的接口配置建模框架
Sep 26 NodeJs
nodejs教程之入门
Nov 21 NodeJs
nodeJS删除文件方法示例
Dec 25 NodeJs
深入nodejs中流(stream)的理解
Mar 27 NodeJs
nodeJS(express4.x)+vue(vue-cli)构建前后端分离实例(带跨域)
Jul 05 NodeJs
基于nodejs+express4.X实现文件下载的实例代码
Jul 13 NodeJs
nodejs项目windows下开机自启动的方法
Nov 22 NodeJs
nodejs+mongodb aggregate级联查询操作示例
Mar 17 NodeJs
通过nodejs 服务器读取HTML文件渲染到页面的方法
May 17 NodeJs
用Electron写个带界面的nodejs爬虫的实现方法
Jan 29 NodeJs
NodeJs生成sitemap站点地图的方法示例
Jun 11 NodeJs
NodeJS的url截取模块url-extract的使用实例
Nov 18 #NodeJs
NodeJS url验证(url-valid)的使用方法
Nov 18 #NodeJs
NodeJS与Mysql的交互示例代码
Aug 18 #NodeJs
利用NodeJS的子进程(child_process)调用系统命令的方法分享
Jun 05 #NodeJs
将nodejs打包工具整合到鼠标右键的方法
May 11 #NodeJs
用nodejs写的一个简单项目打包工具
May 11 #NodeJs
nodejs教程 安装express及配置app.js文件的详细步骤
May 11 #NodeJs
You might like
php的$_FILES的临时储存文件与回收机制实测过程
2013/07/12 PHP
老版本PHP转义Json里的特殊字符的函数
2015/06/08 PHP
PHP实现抽奖功能实例代码
2020/06/30 PHP
理解JavaScript中的事件
2006/09/23 Javascript
javascript面向对象编程(一) 实例代码
2010/06/25 Javascript
使用jQuery+HttpHandler+xml模拟一个三级联动的例子
2011/08/09 Javascript
Javascript的时间戳和php的时间戳转换注意事项
2013/04/12 Javascript
jquery必须知道的一些常用特效方法及使用示例(整理)
2013/06/24 Javascript
javascript中局部变量和全局变量的区别详解
2015/02/27 Javascript
javascript实现类似java中getClass()得到对象类名的方法
2015/07/27 Javascript
复杂的javascript窗口分帧解析
2016/02/19 Javascript
JS模拟实现ECMAScript5新增的数组方法
2017/03/20 Javascript
基于nodejs+express4.X实现文件下载的实例代码
2017/07/13 NodeJs
React Native第三方平台分享的实例(Android,IOS双平台)
2017/08/04 Javascript
AngularJS实现自定义指令及指令配置项的方法
2017/11/20 Javascript
js+canvas实现验证码功能
2020/09/21 Javascript
原生JS实现随机点名项目的实例代码
2019/04/30 Javascript
Vue+Element-U实现分页显示效果
2020/11/15 Javascript
[02:12]打造更好的电竞完美世界:完美盛典回顾篇
2018/12/19 DOTA
Python爬虫抓取手机APP的传输数据
2016/01/22 Python
在Python程序员面试中被问的最多的10道题
2017/12/05 Python
python用线性回归预测股票价格的实现代码
2019/09/04 Python
python——全排列数的生成方式
2020/02/26 Python
python logging 重复写日志问题解决办法详解
2020/08/04 Python
Python爬虫如何破解JS加密的Cookie
2020/11/19 Python
flask项目集成swagger的方法
2020/12/09 Python
The Hut美国/加拿大:英国领先的豪华在线百货商店
2019/03/26 全球购物
毕业生求职简历的自我评价
2013/10/07 职场文书
公司出纳岗位职责
2013/12/07 职场文书
军神教学反思
2014/02/04 职场文书
应届电子商务毕业自荐书范文
2014/02/11 职场文书
信息管理应届生求职信
2014/03/07 职场文书
法人代表证明书格式
2014/10/01 职场文书
个园导游词
2015/02/04 职场文书
实习班主任自我评价
2015/03/11 职场文书
物业工程部主管岗位职责
2015/04/16 职场文书