LoginSignup
0
0

More than 1 year has passed since last update.

GASで「指定のURL」の検索結果をSpreadSheetに一覧記載

Last updated at Posted at 2023-03-27

概要

特に外向けに難しいことを発信しようとしたわけでもなく、今後もたまに使いそうだと思った、GASのスクリプトを備忘しておきます、みたいなシリーズのその3。

「指定のURL」の検索結果をSpreadSheetに一覧記載

function searchAndExportToSpreadsheet() {
  // APIキーとSearchEngineIdを記載
  const apiKey = '(GoogleCloudPlatformで取得のAPIキー)';
  const searchEngineId = '(検索エンジンID)';

  // 検索文字列入れる
  const query = '(検索したい文字列)';

  // SSは新しく作ってしまう
  const ss = SpreadsheetApp.create('Search Results for ' + query);
  const sheet = ss.getActiveSheet();
  sheet.appendRow(['Title', 'URL', 'Snippet']);

  // 取得したいページ数÷10で繰り返し(今回は200件分)
  for (var i = 0; i < 20; i++) {
    let start = i * 10 + 1;

    // 検索APIのURL類似検索結果も対象にするのでfilter=0
    let url = 'https://www.googleapis.com/customsearch/v1?';
    url += 'key=' + apiKey + '&cx=' + searchEngineId + '&q=' + encodeURIComponent(query) + '&start=' + start + '&filter=0';
    let response = UrlFetchApp.fetch(url, { method: 'GET', muteHttpExceptions: true });
    let json = JSON.parse(response.getContentText());

    // 検索結果チェック
    if (!json.items || json.items.length === 0) {
      break;
    }

    // 検索結果ごとに、SSに項目追記
    json.items.forEach(function (item) {
      sheet.appendRow([item.title, item.link, item.snippet]);
    });
  }

  // 作成したSSのURLをログ出力
  Logger.log('Search results spreadsheet created: %s', ss.getUrl());
}

終わり

すいません、ChatGPTに外注して作らせました。

image.png

この程度なら、スクリプト書いてる間に人の手でやったほうが早い説もある。質問投げてるだけでちょっとずつチューニングしてくれるのは楽というところか。

0
0
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
0
0