Google Apps Script 抓 RSS 資料

Google Apps Script 抓 RSS 資料
Google Apps Script 抓 RSS 資料

本篇要解決的問題

最近正在幫之前開發的 生活小幫手 把放在 GCP 上的 Node.js 功能陸續搬到 Google Apps Script 上,因為免費額過了開始收到繳費單 == ,想看搬上 GAS 後會不會讓使用額度是在免費以內。

在搬功能的時候,發現有幾個功能是要抓 RSS 的資料來發送,就查了一下 GAS 是否也可以抓 RSS / XML 的資料,查完後還發現真的有,而且實際使用後也抓成功了,就筆記成這篇。


選定要抓的 RSS 資料

本篇的練習我們找中央社的國際新聞 RSS,主要是因為最近看烏俄戰爭的新聞很常看他們家寫的。

他們的網站有一頁就是 RSS 列表:中央通訊社RSS服務

點擊「國際」後會打開這個網址:https://feeds.feedburner.com/rsscna/intworld

這個網址就是國際新聞的 RSS 網址,我們下一步在 Google Apps Script 上抓這個網址就行。


Google Apps Script 上抓 RSS 資料

在 Google 雲端硬碟上開好一份 Google Apps Script 的檔案(以下簡稱 GAS),命好檔名後便會自動儲存 GAS 檔案,我們再把上一步取得的 RSS 網址設成變數,然後命一個函式來準備抓資料:

// 中央社國際新聞 RSS 網址
const rss = 'https://feeds.feedburner.com/rsscna/intworld';
function getRSS() {
  // 準備來抓資料
}

GAS 上抓 RSS / XML 的文件在這:XML Service

文件上已經寫好了範例的程式碼:

function parseXml() {
  let url = 'https://blog.google/rss/';
  let xml = UrlFetchApp.fetch(url).getContentText();
  let document = XmlService.parse(xml);
  let root = document.getRootElement();

  let channel = root.getChild('channel');
  let items = channel.getChildren('item');
  items.forEach(item => {
    let title = item.getChild('title').getText();
    let categories = item.getChildren('category');
    let labels = categories.map(category => category.getText());
    console.log('%s (%s)', title, labels.join(', '));
  });
}

看了這段範例後才發現,蝦米!GAS 也支援 ES6 啦~~~

好的,看到範例,就可以之到基本抓出 RSS 資料,有三行是固定要有的:

let xml = UrlFetchApp.fetch(要抓的 RSS 網址).getContentText();
let document = XmlService.parse(xml);
let root = document.getRootElement();

之後就是看 RSS 上的 XML 資料格式,用 root.getChild(欄位名稱) 去抓取就行。

我們先在中央社的 RSS 頁面上點右鍵看一下原始碼,會看到這樣:

可以看到結構是 <channel> 裡面包著 <item><item> 就是我們要抓取的每一則新聞,包含標題、連結、日期、描述。其實 RSS 有一套撰寫規則,大家可以在 W3school 上觀看說明。

這邊 August 直接修改 GAS 文件上的範例程式碼,我們取第一個 <item> 的資料就好:

const rss = 'https://feeds.feedburner.com/rsscna/intworld';
function getRSS() {
  let xml = UrlFetchApp.fetch(rss).getContentText();
  let document = XmlService.parse(xml);
  let root = document.getRootElement();

  let channel = root.getChild('channel');
  let item = channel.getChildren('item')[0];

  let title = item.getChild('title').getText();
  let link = item.getChild('link').getText();
  let pubDate = item.getChild('pubDate').getText();

  console.log(title);
  console.log(link);
  console.log(pubDate);
}

寫好程式碼後,我們按上方選單的「執行」,會看到以下輸出:

執行 getRSS 看輸出
執行 getRSS 看輸出

鏘鏘~有看到輸出結果,就代表我們資料抓取成功啦。

GAS 的文件上有各個參數的說明,想了解更多的朋友請自行觀看啦:XML Service

Summary
Google Apps Script 抓 RSS 資料
Article Name
Google Apps Script 抓 RSS 資料
Description
學習如何使用 Google Apps Script 在 WordPress 上抓取 RSS 資料。本文以中央通訊社的國際新聞 RSS 為例,提供了詳細的步驟指南和實用技巧,助你輕鬆抓取和處理 RSS 數據。
August
Let's Write
Let's Write
https://letswritetw.github.io/letswritetw/dist/img/logo_512.png
訂閱
通知
guest

0 Comments
最舊
最新
Inline Feedbacks
看所有留言