2016年12月31日土曜日

google news RSS feedを google feed APIを用いて JSONデータとして取得するJavaScript

2017 Jan. 08.
2016 Dec. 31.

URL書式

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=件数&q=GOOGLE-NEWS-RSS-URL
  "q=GOOGLE-NEWS-RSS-URL"を最後に記述する。"num=件数"よりも前に"q=GOOGLE-NEWS-RSS-URL"を記述すると失敗する。
  GOOGLE-NEWS-RSS-URL の部分の文字は HTML URL Encoding に置き換える。
    & -> %26
    : -> %3A
    = -> %3D
    ? -> %3F

JSONデータ構造

( http://www.ctrlshift.net/jsonprettyprinter/ を利用 )
{
    "responseData": {
        "feed": {
            "author": "",
            "description": "News",
            "entries": [
                {
                    "author": "",
                    "categories": [
                        "Top Stories"
                    ],
                    "content": "<table border="0" ><xxx>",
                    "contentSnippet": "新聞の ...",
                    "link": "http://xxx.html",
                    "publishedDate": "Fri, 30 Dec 2016 22:59:17 -0800",
                    "title": "xxxのニュース"
            },
               [
                {
                    "author": "",
                    "categories": [
                        "Stories"
                    ],
                    "content": "<table border="0" ><yyy>",
                    "contentSnippet": "新の ...",
                    "link": "http://yyy.html",
                    "publishedDate": "Fri, 30 Dec 2016 23:00:17 -0800",
                    "title": "yyyのニュース"
                }

            ],
            "feedUrl": "https://news.google.com/news?ned=us&hl=ja&output=rss",
            "link": "http://news.google.com/news?hl=ja&amp;ned=us",
            "title": "Top Stories - Google News",
            "type": "rss20"
        }
    },
    "responseDetails": null,
    "responseStatus": 200
}

JavaScript サンプル


function fetchGoogleNewsJson() {
  var url = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=https%3A//news.google.com/news%3Fned%3Dus%26hl%3Dja%26output%3Drss';
    // HTML URL Encoding
    //   q=https%3A//news.google.com/news%3Fned%3Dus%26hl%3Dja%26output%3Drss
    //    ↑
    //   q=https://news.google.com/news?ned=us&hl=ja&output=rss

  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText();
  var data = JSON.parse(json);
  var fetchText = "";
  if (data.responseData.feed.entries) {
    for( var i=0 ; i < data.responseData.feed.entries.length; i++){
      fetchText = fetchText + data.responseData.feed.entries[i].title + "\n" + data.responseData.feed.entries[i].publishedDate.slice(5,-9) + "\n\n";
    }
  }
  return fetchText;
}

0 件のコメント:

コメントを投稿