0
1

RSSとAtom 記事一覧の取得方法の話

Posted at

はじめに

複数のプラットフォームから記事一覧を取得したい!
なるべく処理を共通化したい!

RSS1.0 / RSS2.0 / Atom

こちらの記事がとても参考になります。
記事情報の取得(Feed)のための仕組みは3種類あるようです。

仕組み 採用プラットフォーム タイトルの取得方法
RSS1.0
RSS2.0 Zenn / しずかなインターネット / note channel > item > title
Atom Qiita / Github(コミット情報) entry > title

同じ仕組みを採用している場合、処理を共通化することができます。

共通化した処理

プラットフォームごとのURLを受け取り、共通化された処理を行います。

返り値は{title:string, link:string, published:date}です。

仕組みによりますが、以下の要素も取得可能です。

  • description:書き出し等
  • enclosure:見出し画像
  • author:著者
  • updated:更新日時

RSS2.0の場合(GAS)

const getRss2 = (url) => {
  // RSSフィードを取得
  const response = UrlFetchApp.fetch(url);
  const xml = response.getContentText();
  
  // XMLをパース
  const document = XmlService.parse(xml);
  const items = document.getRootElement().getChild('channel').getChildren('item');

  // 連想配列のリストを作成
  const feedData = items.map(item => {
    const title = item.getChild('title').getText();
    const link = item.getChild('link').getText();
    const published = item.getChild('pubDate').getText();
    
    return {
      title: title,
      link: link,
      published: published
    };
  });

  return feedData;
}

Atomの場合

const getAtom = (url) => {
  const response = UrlFetchApp.fetch(url);
  const xml = response.getContentText();
  
  // XMLをパース
  const document = XmlService.parse(xml);
  const entries = document.getRootElement().getChildren('entry', XmlService.getNamespace('http://www.w3.org/2005/Atom'));

  // 連想配列のリストを作成
  const feedData = entries.map(entry => {
    const title = entry.getChild('title', XmlService.getNamespace('http://www.w3.org/2005/Atom')).getText();
    const link = entry.getChild('link', XmlService.getNamespace('http://www.w3.org/2005/Atom')).getAttribute('href').getValue();
    const published = entry.getChild('published', XmlService.getNamespace('http://www.w3.org/2005/Atom')).getText();
    
    return {
      title: title,
      link: link,
      published: published
    };
  });
  return feedData;
}

linkの取得

RSS2.0

<link>
  https://sizu.me/kohki_takatama/posts/uw2ce6ntoa99
</link>

Atom

<link
  rel="alternate"
  type="text/html"
  href="https://qiita.com/kohki_takatama/items/9b319e83a00c491baf2a"
/>

このように、linkの記述方法が異なり、取得方法も変わります。
Atomはurlタグで取得することも可能です。

参考記事

各サイトのFeed URL

Feedの種類

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1