Example Request

node `${file_name}.js` `${bus_route_number}` 
// node showBusTime.js 207

Example Response

東南客運停車場 未發車

新湖一路口 未發車

潭美國小(舊宗) 未發車

週美里一 未發車

玉成里(東新街) 將到站

聯合醫院忠孝院區 將到站

合心廣場 將到站

捷運後山埤站(忠孝) 3分

協和祐德高中 4分

玉成公園(中坡) 5分

奉天宮 7分

松友新村 交管不停

松山商職(福德) 8分

國業里 9分

國稅局宿舍 10分

捷運象山站 11分

信義行政中心(信義) 13分

捷運台北101/世貿站(信義) 14分

吳興街口 17分

三興國小(臨江街觀光夜市) 19分

喬治商職 19分

捷運六張犁站(基隆路) 21分

和平高中 22分

基隆長興街口 24分

臺大癌醫(基隆路) 25分

臺灣科技大學 26分

公館 27分

福和橋(林森路) 將到站

永元路 將到站

秀朗國小 將到站

得和路 3分

中興新村 4分

中興二村 5分

智光商職 7分

南勢角(興南路) 8分

捷運南勢角站 9分

程式碼

const BASE_URL = 'https://pda.5284.gov.taipei/MQS/businfo2.jsp?routename='
const request = require('request')
const number = process.argv[2]

// 發送請求取得頁面上所有資料,再將 response.body 傳入 getBusData()
function getBusData(number, callback) {
  request(
    `${BASE_URL}${number}`, (err, response) => {
      if (err) {
        callback(err)
        return
      }

      callback(null, response.body)
    }
  )
}

// 呼叫並取得公車資料,console.log 出最終結果
getBusData(number, (err, html) => {
  if (err) {
    return console.log(err)
  }

  let result = getStopInfo(html)
  console.log(result.join('\n'))
})

// 取得公車資訊:把字串給切出來
function getStopInfo(html) {
  let result = []
  let start = 0
  let end

  // 重複切出字串
  while (start >= 0) {
    start = html.indexOf('<tr class="ttego', start + 1)
    end = html.indexOf('</tr>', start)
    let strWithAnchor = html.slice(start , end)

    // 將切出的字串傳入 parseData() 後繼續切出目標資訊字串
    let data = parseData(strWithAnchor)
    result.push(data.name + ' ' + data.time)
  } 

  return result
}

// 切出目標資訊:站名與到站時間
function parseData(str) {
  let leftBracket = str.indexOf('<a')
  let rightBracket = str.indexOf('>', leftBracket)
  let anchorEnd = str.indexOf('</a>', rightBracket + 1)

  let name = str.slice(rightBracket + 1, anchorEnd)

  let nowrap = str.indexOf('nowrap>')
  let end = str.indexOf('<', nowrap)

  let time = str.slice(nowrap + 7, end)

  // ES6 語法中,若 key-value 名稱一樣,寫一次即可
  let result = {
    name,
    time
  }
  return result
}


參考資源


#程式導師實驗計畫第四期 #前端 #公車即時動態







Related Posts

01. Install Python, Flask and virtual environment

01. Install Python, Flask and virtual environment

Create a role when first starting up the PostgreSQL DB

Create a role when first starting up the PostgreSQL DB

[Py 百日馬 Day 3] 用 if / elif / else 見機行事

[Py 百日馬 Day 3] 用 if / elif / else 見機行事


Comments