Node.js 爬蟲練習 - 牌告匯率
在網路上亂逛的時候,發現可以利用 Node.js 來爬蟲,
那麼,就讓我們拿臺銀的匯率網頁來做練習吧!
這次的練習需要以下 4 個套件:
支援 Windows / macOS / Linux,可至官網下載。
安裝完成後,開啟命令列檢查環境變數設定是否正常:
(以 Windows 為例,Start -> 附屬應用程式 -> 命令提示字元)
輸入:
安裝指令:
特色:解析速度非常快!
安裝指令:
安裝指令:
將以上程式碼存為 index.js 並放置於目錄中
利用上述指令安裝套件後,
執行
執行結果如下:
[註] 因為 VSCode debug 模式執行一次後就會結束程序,
所以無法執行此定時執行功能喔
第一個爬蟲程式完成囉~~
實際上要當專業爬蟲還有很多咩剛,
往後再來深入研究
那麼,就讓我們拿臺銀的匯率網頁來做練習吧!
這次的練習需要以下 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
完整程式碼
- // import necessary libraries
- const request = require('request');
- const cheerio = require('cheerio');
- const schedule = require('node-schedule');
- // seed for web crawling
- const url = "http://rate.bot.com.tw/xrt?Lang=zh-TW";
- /**
- * get the content for the url and parse it
- */
- function getCurrency() {
- // send http request
- request(url, (err, res, body) => {
- // convert the content string to DOM
- var $ = cheerio.load(body);
- // get the rate element
- $("td.rate-content-cash").each(function (idx, element) {
- let $element = $(element);
- if ($element.data("table") === "本行現金賣出" && !!+$element.text()) {
- // name of currency
- var currency = $($element.siblings()[0]).text().trim();
- // name is duplicated, we only need one
- var currency = currency.split(" ")[0];
- switch(currency){
- case "日圓": // we are interesting in
- console.log(currency + "\t:" + $element.text());
- break;
- default:
- break;
- }
- }
- });
- // get system beep (just for fun XD)
- process.stdout.write('\x07');
- console.log("===================================================");
- });
- }
- function scheduleCronstyle(){
- // parse every 5 seconds
- schedule.scheduleJob('*/5 * * * * *', function(){
- getCurrency();
- });
- }
- scheduleCronstyle();
使用方法:
建立新目錄(例:D:\spider-currency),將以上程式碼存為 index.js 並放置於目錄中
利用上述指令安裝套件後,
執行
node index.js
執行結果如下:
[註] 因為 VSCode debug 模式執行一次後就會結束程序,
所以無法執行此定時執行功能喔
第一個爬蟲程式完成囉~~
實際上要當專業爬蟲還有很多咩剛,
往後再來深入研究
留言