Google Apps Scriptとcheeriogsでaタグの属性をすべて取得する方法

cheeriogsとは

GASで使用可能なHTMLをパースできるライブラリ。

使い方は以前の記事を参照

GASでaタグの属性を取得

Google Apps Scriptでaタグの属性を取得する場合は以下のようなコードになる。

HTML5を使用している場合は廃止されている属性が付いていないかチェックしたほうが良いだろう。

function myFunction() {
  const sheet = SpreadsheetApp.getActiveSheet()
  const url = sheet.getRange('B1').getValue().trim()
  sheet.getRange("A2:D1000").clearContent();
  if (!url || !/^http/.test(url)) return

  const content = UrlFetchApp.fetch(url).getContentText()
  const $ = Cheerio.load(content)
  const $a = $('a')
  const domain = url.split('/')[2]
  const attrs = [
    'name',
    'charset',
    'coords',
    'shape',
    'rev'
  ]

  if ($a.length) {
    $a.each((i, v) => {
      const forbiddenAttrs = attrs.reduce((a, c) => {
        if ($(v).attr(c)) {
          a.push(c)
        }
        return a
      }, [])
      sheet.getRange(i + 2, 1).setValue($(v).attr('href'))
      sheet.getRange(i + 2, 2).setValue($(v).attr('target'))
      sheet.getRange(i + 2, 3).setValue($(v).text().replace(/\n/gm, '').trim())
      sheet.getRange(i + 2, 4).setValue($(v).attr('rel'))
      sheet.getRange(i + 2, 5).setValue(forbiddenAttrs.join(', '));
    })
  } else {
    sheet.getRange(2, 1).setValue('aタグは存在しません。')
  }
}

Google Apps Scriptで画像とaを取得するサンプル