使用PhantomJS桥序列化函数

Serialize function with PhantomJS bridge

本文关键字:函数 序列化 PhantomJS 使用      更新时间:2023-09-26

我有一个链接数组,这些链接使用链接parameter作为函数,该函数通过PhantomJS抓取数据。如何将此功能系列化?此for语句一次并行运行3个函数,并且我收到事件错误

在这种情况下,使用async是合适的,但它如何在串行中使用?运行函数的时间总是不同的,但async应该如何理解它已经完成并从新的URL开始?

var phantom = require('phantom')
  , async = require('async');
var urls = [
  'http://en.wikipedia.org/wiki/Main_Page',
  'http://es.wikipedia.org/wiki/Wikipedia:Portada',
  'http://de.wikipedia.org/wiki/Wikipedia:Hauptseite'
];
async.mapSeries(urls, getTitle, function(err, result){
    console.log(result);
})
function getTitle (link, callback) {
  phantom.create(function(ph) {
    return ph.createPage(function(page) {
      return page.open(link, function(status) {
        return page.evaluate((function() {
          return document.title;
        }), function(result) {
          callback(null, result);
          return ph.exit();
        });
      });
    });
  });
};

我会尝试这样的东西:

var links = []
var _ph
function init(cb) {
    phantom.create(function(ph) {
        //for each link in links call doStuff()
        _ph = ph 
        doStuff(ph, link, cb)   
    })   
}
function doStuff(ph, link, cb) {
    ph.createPage(function(page) { //does things in parallel?
      page.open(link, function(status) {
        page.evaluate((function() {
          document.title;
        }), function(result) {
          cb(null, result);
          page.close();
        });
    });
}
var counter = links.length
var titles;
function results(err, res) {
  titles.push(res)
  if(--counter == 0) {
    //done
    _ph.exit()
  }
 }
init(results)

可能不工作代码(我在这里写的),但我希望你能明白这个想法。如果你只想使用一页,比如:

var links = []
var _ph
var _page
function init(cb) {
    phantom.create(function(ph) {
        _ph = ph 
        ph.createPage(function(page) {
             _page = page
             doStuff(link, cb)
        }   
    })   
}
function doStuff(page, link, cb) {
      page.open(link, function(status) {
        page.evaluate((function() {
          document.title;
        }), function(result) {
          cb(null, result);
          page.close();
        });
    });
}
 var counter = links.length
var titles;
function results(err, res) {
  titles.push(res)
  if(--counter == 0) {
    //done
    _ph.exit()
    return
  }
  doStuff(links[counter], results)
 }
init(results)