2013-02-09 42 views
12

我可以用meteor.js刮?剛剛發現cheerio,它與request結合非常出色。我可以使用這些流星,還是有類似的東西?刮Meteor.js

你有一個工作的例子嗎?

+0

類似,如果不重複:http://stackoverflow.com/questions/15034453/how-can-one-parse-html-server-side-with-meteor – 2014-04-22 12:19:22

+0

這個問題啓發了我記錄相關的截屏視頻:https://www.youtube.com/watch?v = QA0_0SPd3P8謝謝! – DeBraid 2015-03-27 18:32:48

回答

20

當然!很難想象流星不能做什麼!首先你需要一些東西來處理遠程http請求。在終端運行您的流星目錄meteor add http添加Meteor.http包,也npm install cheerio(看看another SO question on how to install npm modules,看看到底哪裏安裝外部NPM模塊。

下面是一個例子,可以幫助你出去了一下,刮痧current time

服務器JS

require = __meteor_bootstrap__.require; //to use npm require must be exposed. 
var cheerio = require('cheerio'); 

Meteor.methods({ 
    getTime: function() { 
     result = Meteor.http.get("http://www.timeanddate.com/worldclock/city.html?n=136"); 
     $ = cheerio.load(result.content); 
     CurrentTime = $('#ct').html(); 
     return CurrentTime; 
    } 
}); 

客戶端腳本:

Meteor.call("getTime", function(error, result) { 
    alert("The current time is " + result); 
}); 

我希望這是有幫助的。 Cheerio中還有其他節點框架,如node.io

+0

你有什麼建議模擬JS刮?你的例子看起來像只有HTML – FullStack 2015-02-12 08:53:13

+0

@FullStack如果你需要進行更高級的抓取,請查看使用phantomjs。 – Akshat 2015-02-12 09:05:22

1

下面的代碼在this project用於刮tweetstorm:

if (Meteor.isClient) { 

    Meteor.call('getTweets', function (error, result) { 
    if (error) { 
     console.log("error", error); 
    }; 

    Session.set("tweets", result); 
    }); 

    Template.tweets.helpers({ 
    rant: function() { 
     return Session.get("tweets"); 
    } 
    }); 

} 

服務器側

if (Meteor.isServer) { 
     Meteor.startup(function() { 
     var cheerio = Meteor.npmRequire('cheerio'); 

    Meteor.methods({ 
     getTweets: function() { 
     result = Meteor.http.get("https://twitter.com/Royal_Arse/status/538330380273979393"); 
     $ = cheerio.load(result.content); 
     var body = $('#stream-items-id > li:nth-child(n) > div > div > p').text(); 
     return body; 
     }, 

    }) 

    }); 
}