Google Apps Script でスクレイピング 〜 ページ内に特定の文字列が含まれているか判定する
- 2017 4/22
- カテゴリー : Google Apps Script
- スクレイピング
- コメントを書く
Google Apps Script ページ内に特定の文字列が含まれているかを判定するスクレイピングみたいなコードを書いたのでご紹介します。
コードの処理の流れ
- UrlFetchApp.fetch でレスポンスを取得する
- response.getContentText で HTTP response のコンテンツをエンコード済みの文字列で取得する
- String.prototype.indexOf() で文字列に ‘Example’ を含んでいるか判定する
Google Apps Script のサンプルコード
function myFunction() { var contentText = fetchContentText("http://example.com"); if (contentText.indexOf('Example') !== -1) { Logger.log('◯'); } else { Logger.log('☓'); } } function fetchContentText(url){ var opt = {"contentType":"text/html","method":"get"}; var response = UrlFetchApp.fetch(url, opt); var contentText = response.getContentText(); return contentText; } |
基本的なスクレイピングは少しのコードで実現できました。
このコードを元に、次は判定結果を Google スプレッドシートに追記していくコードを書けば利用の幅が広がる気がしています。
参考情報
- Class UrlFetchApp | Apps Script | Google Developers
- Class HTTPResponse | Apps Script | Google Developers
- Class Logger | Apps Script | Google Developers
- String.prototype.indexOf() – JavaScript | MDN