Node.js 爬蟲練習 - 牌告匯率

在網路上亂逛的時候,發現可以利用 Node.js 來爬蟲,
那麼,就讓我們拿臺銀的匯率網頁來做練習吧!

這次的練習需要以下 4 個套件:

嗯,這是必備條件 (廢話 XD
支援 Windows / macOS / Linux,可至官網下載。
安裝完成後,開啟命令列檢查環境變數設定是否正常:
(以 Windows 為例,Start -> 附屬應用程式 -> 命令提示字元)
輸入:
node --version
目前最新的穩定版本為:8.11.1


模擬瀏覽器,發送 http 請求(也支援 https )、接收回應,用來取得網頁內容
安裝指令:
npm install request

提供 jQuery方式取得 DOM 結構內容。
特色:解析速度非常快!
安裝指令:
npm install cheerio

Node.js 的排程套件,可在指定時間、期間、定時執行。
安裝指令:
npm install node-schedule

完整程式碼

  1. // import necessary libraries
  2. const request = require('request');
  3. const cheerio = require('cheerio');
  4. const schedule = require('node-schedule');
  5.  
  6. // seed for web crawling
  7. const url = "http://rate.bot.com.tw/xrt?Lang=zh-TW";
  8.  
  9. /**
  10. * get the content for the url and parse it
  11. */
  12. function getCurrency() {
  13. // send http request
  14. request(url, (err, res, body) => {
  15. // convert the content string to DOM
  16. var $ = cheerio.load(body);
  17.  
  18. // get the rate element
  19. $("td.rate-content-cash").each(function (idx, element) {
  20. let $element = $(element);
  21. if ($element.data("table") === "本行現金賣出" && !!+$element.text()) {
  22. // name of currency
  23. var currency = $($element.siblings()[0]).text().trim();
  24. // name is duplicated, we only need one
  25. var currency = currency.split(" ")[0];
  26. switch(currency){
  27. case "日圓": // we are interesting in
  28. console.log(currency + "\t:" + $element.text());
  29. break;
  30.  
  31. default:
  32. break;
  33. }
  34. }
  35. });
  36. // get system beep (just for fun XD)
  37. process.stdout.write('\x07');
  38. console.log("===================================================");
  39. });
  40. }
  41.  
  42. function scheduleCronstyle(){
  43. // parse every 5 seconds
  44. schedule.scheduleJob('*/5 * * * * *', function(){
  45. getCurrency();
  46. });
  47. }
  48.  
  49. scheduleCronstyle();


使用方法:

建立新目錄(例:D:\spider-currency),
將以上程式碼存為 index.js 並放置於目錄中
利用上述指令安裝套件後,
執行
node index.js

執行結果如下:

[註] 因為 VSCode debug 模式執行一次後就會結束程序,
所以無法執行此定時執行功能喔

第一個爬蟲程式完成囉~~
實際上要當專業爬蟲還有很多咩剛,
往後再來深入研究

留言