LoginSignup
3
4

More than 1 year has passed since last update.

【GASでスクレイピング入門】connpassのイベントランキング(1位から50位)を毎日スプレッドシートに保存して学ぼう

Last updated at Posted at 2021-08-20

image.png

YouTubeでの解説: https://youtu.be/fvqSOkI7dBI

スクレイピングで気をつける点の参考サイト:https://topcourt-law.com/internet_security/scraping-illegal/
参考記事①:https://qiita.com/zumi0/items/59a3f3a964cf1dbc45c1
参考記事②:https://specially198.com/scraping-with-gas-using-parser-library/

スプレッドシートを用意

https://spreadsheet.new
上記URLから空のスプレッドシートを開き
- A列に「順位」
- B列に「タイトル」
- C列に「URL」
としておきます。

スクリーンショット 2021-10-20 11.45.43.png

スクリプトエディタを開く

上のツールからスクリプトエディタを選択すると、別タブが開きプログラムを書くことができるページが開きます。
スクリーンショット 2021-10-20 11.50.20.png

connpassのページのランキング50位を取得するプログラム

新しくタブが開いたら、3行のコード(myFunctionの空の関数)が書かれているのですが、使わないで3行全部消して、下記のコードをコピペしてください。

コード.gs
const SHEET = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/***************/edit').getSheetByName('シート1')

function perserTest() {

  const url = 'https://connpass.com/ranking/'
  const html = UrlFetchApp.fetch(url).getContentText('utf-8')
  const events_title = Parser.data(html).from('<p class="event_title">\n').to('</p>').iterate()
  let event_title, event_url

  deleteTest()

  for (i in events_title) {

    event_title = events_title[i].replace(/<a.*">/, "")
    event_title = event_title.replace(/    /g, "")
    event_title = event_title.replace(/ /g, "")
    event_title = event_title.replace('</a>', "")
    event_title = event_title.replace('\n', "")

    event_url = events_title[i].replace(/<a href="/, "")
    event_url = event_url.replace(/">.*<\/a>/g, "")
    event_url = event_url.replace(/    /g, "")
    event_url = event_url.replace(/ /g, "")
    event_url = event_url.replace('\n', "")

    SHEET.appendRow([Number(i) + 1, event_title, event_url])

  }

}

function deleteTest() {

  SHEET.deleteRows(2,50)

}

また、今回はスクレイピング用のライブラリを使用するので、下記のライブラリIDを、左上のライブラリの横にある「+」マークから追加してください。
ParserのライブラリID:1Mc8BthYthXx6CoIz90-JiSzSafVnT6U3t0z_W3hLTAX5ek4w0G_EIrNw
スクリーンショット 2021-10-20 11.55.34.png

次に、左上の時計マークを押して、右下の「トリガーを追加」を押して、実行する関数 perserTest 時間手動型の日付ベースのタイマーで毎日実行するトリガーに設定してあげたら完成です。

スクリーンショット 2021-10-20 11.58.46.png

完成

これで、connpassのイベントランキング(1位から50位)を毎日スプレッドシートに保存できると思います。
この情報を使って、何かサービスを作っても楽しいかもしれませんね。

スクリーンショット 2021-10-20 11.46.00.png

スクレイピング先のページと規約

スクレイピング先のページ:https://connpass.com/ranking/
スクレイピング先の利用規約:https://connpass.com/term/

さいごに

Udemy講師もやっているので、ご購入いただけるととても嬉しいです!

◆ Udemy「Google Apps Scriptの基礎を学ぶ講座」
https://www.udemy.com/course/googleappsscript/

◆ Udemy「Web APIとスクレイピングを使ってLINE BOTをつくる講座」
https://www.udemy.com/course/web-api-scraping-gas-linebot-tsfcm/

3
4
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
4