3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GASでrssやatom(Google News)を読み込む

Last updated at Posted at 2017-11-03

##RSS

var rss = XmlService.getNamespace('http://purl.org/rss/1.0/')
var dc = XmlService.getNamespace('dc', 'http://purl.org/dc/elements/1.1/')

function readRss(url) {
  var sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName('シート1')

  // フィードを取得
  var response = UrlFetchApp.fetch(url).getContentText()
  
  // XMLをパース
  var xml = XmlService.parse(response)
  var root = xml.getRootElement()
  var items = root.getChildren('item', rss)
  
  // 読み込んだデータをスプレッドシートに出力
  sheet.clear()
  for (var i = 0; i < items.length; i++) {
    var title = items[i].getChild('title', rss).getText()
    var link = items[i].getChild('link', rss).getText()
    var date = Utilities.formatDate(new Date(items[i].getChild('date', dc).getText()), 'Asia/Tokyo', 'yyyy/MM/dd')

    sheet.getRange(i + 1, 1).setValue(title)
    sheet.getRange(i + 1, 2).setValue(link)
    sheet.getRange(i + 1, 3).setValue(date)
  }
}

※SHEET_IDにはスプレッドシートのIDをつかってください。

##atom
ここではGoogle Newsを例にとります。

function getATOM(query) {
  var sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName('シート2')

  var feedURL= 'https://news.google.com/news/?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=atom&num=30&hl=ja&gl=JP&ceid=JP:ja&q=' + query

  var xml = UrlFetchApp.fetch(feedURL).getContentText()
  var document = XmlService.parse(xml)
  var root = document.getRootElement()
  var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom')

  var entries = root.getChildren('entry', atom)
  sheet.clear()
  for (var i = 0; i < entries.length; i++) {
    var title = entries[i].getChild('title', atom).getText()
    var link = entries[i].getChild('link', atom).getAttribute('href').getValue()
    var updated = entries[i].getChild('updated', atom).getText()
    var date = Utilities.formatDate(new Date(updated), 'Asia/Tokyo', 'yyyy/MM/dd HH:mm')

    sheet.getRange(i + 1, 1).setValue(title)
    sheet.getRange(i + 1, 2).setValue(link)
    sheet.getRange(i + 1, 3).setValue(date)

    // 画像があれば抽出
    var content = entries[i].getChild('content', atom).getText()
    var start = content.indexOf('img src="')
    if (start >= 0) {
      var end = content.indexOf('"', start + 9)
      var imageUrl = content.substring(start + 9, end)
      sheet.getRange(i + 1, 4).setValue('https:' + imageUrl)
    } else {
      sheet.getRange(i + 1, 4).setValue('');
    }
  }
}
3
8
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
3
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?