2012年3月23日 星期五

Node.js - 使用jsdom抓取中央氣象局即時天氣

 

源由:

透過Node.js定時更新天氣資訊。雖說中央氣象局的即時天氣頁面在這裡可以查詢,但整個頁面看來相當複雜,心中不免一陣OS,不過稍微看了一下html結構後可以發現這頁只是展示頁,其資料內容是javascript產生的,再深入了解了一下可以發現其資料來源是放在這裡。好了,這頁看起來簡單多了,開始動手吧 :)

環境:

Node.js: v0.6.12
jsdom: v0.2.13
mongodb: v1.8.2
mongoose: v2.5.9

不說廢話,直接進入程式碼

var jsdom = require('jsdom')

function getWeather() {
  jsdom.env("http://www.cwb.gov.tw/V7/observe/real/ALL.htm",
      ["http://code.jquery.com/jquery-1.7.1.min.js"], function (err, window) {
   
    var $ = window.$;
    var weatherList = [] ;
   
    var tr = $('.BoxTable tr') ;
    var total = tr.length - 1;
    var count = 0 ;

    $('.BoxTable tr').each(function() {

      var th = $(this).find("th") ;

      if("測站" != th.eq(0).text()) {

        var td = $(this).find("td") ;

        var windParams = td.eq(4).text().split("|");
        var windPeakParams = td.eq(5).text().split("|");     
        var weather = {
          location: th.eq(0).text(),
          update: th.eq(1).text(),
          temperature: parseFloat(td.eq(0).text()),
          description: td.eq(2).text(),
          wind:{
            direction: td.eq(3).text(),
            speed: parseFloat(windParams[0]),
            level: parseFloat(windParams[1]),
            peakSpeed: parseFloat(windPeakParams[0]),
            peakLevel: parseFloat(windPeakParams[1]),
          },
         vision: parseFloat(td.eq(6).text()),
         humidity: parseFloat(td.eq(7).text()),
         raining: parseFloat(td.eq(9).text())
        }

        weatherList.push(weather);
        count++;

        if (count==total){
        count = 0;
        var weathers = conn.model("weathers",Weather);  // mongoose model
        for (var w in weatherList) {
          var weather =  weatherList[w];

          weathers.update(
            {"location":weather.location}, // conditions
            weather, //  doc
            {"upsert":true}, // options
            function (err, numAffected){
              count++ ;
              if (count==total){
                console.log(“PASS”);
              }
          });
        }
        }
    }); 
  })
}

以上,只要在node.js定時的呼叫更新即可擁有中央氣象局的天氣資料了。

沒有留言:

張貼留言