代码之家  ›  专栏  ›  技术社区  ›  khex

使用PhantomJS桥序列化函数

  •  1
  • khex  · 技术社区  · 12 年前

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

    在这种情况下,使用它是正确的 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();
            });
          });
        });
      });
    };
    
    1 回复  |  直到 12 年前
        1
  •  1
  •   fusio    12 年前

    我会试试这样的东西:

    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)
    
    推荐文章