const BATCH_SIZE = 100; // 一度に処理する件数(変更可能)

function fetchAllYahooCountsInBatches() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const lastRow = sheet.getLastRow();
  const keywords = sheet.getRange(1, 1, lastRow).getValues();
  const allintitleResults = sheet.getRange(1, 3, lastRow).getValues(); // C列
  const intitleResults = sheet.getRange(1, 4, lastRow).getValues();    // D列

  let processedCount = 0;

  for (let i = 0; i < lastRow; i++) {
    const keyword = keywords[i][0];
    const allCell = allintitleResults[i][0];
    const intCell = intitleResults[i][0];

    // すでに処理済みならスキップ(C列とD列が両方空のときのみ処理)
    if (!keyword || (allCell && intCell)) continue;

    try {
      // allintitle 検索 → C列(3)
      const allQuery = encodeURIComponent("allintitle:" + keyword);
      const allUrl = `https://search.yahoo.co.jp/search?p=${allQuery}`;
      const allHtml = UrlFetchApp.fetch(allUrl, { muteHttpExceptions: true }).getContentText();
      const allMatch = allHtml.match(/約([\d,]+)件/);
      const allResult = allMatch ? allMatch[1].replace(/,/g, '') : 0;
      sheet.getRange(i + 1, 3).setValue(allResult); // C列

      // note.com の存在チェック → E列(5)
      const noteValue = allHtml.includes("note.com") ? "note:〇" : "";
      sheet.getRange(i + 1, 5).setValue(noteValue); // E列

      // chiebukuro.yahoo.co.jp の存在チェック → F列(6)
      const chiebukuroValue = allHtml.includes("chiebukuro.yahoo.co.jp") ? "知恵袋:〇" : "";
      sheet.getRange(i + 1, 6).setValue(chiebukuroValue); // F列

      Utilities.sleep(1000);

      // intitle 検索 → D列(4)
      const intQuery = encodeURIComponent("intitle:" + keyword);
      const intUrl = `https://search.yahoo.co.jp/search?p=${intQuery}`;
      const intHtml = UrlFetchApp.fetch(intUrl, { muteHttpExceptions: true }).getContentText();
      const intMatch = intHtml.match(/約([\d,]+)件/);
      const intResult = intMatch ? intMatch[1].replace(/,/g, '') : 0;
      sheet.getRange(i + 1, 4).setValue(intResult); // D列

      Utilities.sleep(1000);
    } catch (e) {
      Logger.log(`Error at row ${i + 1}: ${e.message}`);
      sheet.getRange(i + 1, 3).setValue("Error");
      sheet.getRange(i + 1, 4).setValue("Error");
      sheet.getRange(i + 1, 5).setValue("Error");
      sheet.getRange(i + 1, 6).setValue("Error");
    }

    processedCount++;
    if (processedCount >= BATCH_SIZE) break; // バッチ制限に達したら終了
  }

  Logger.log(`✅ 処理済み件数: ${processedCount}`);
}


タイトルとURLをコピーしました