Use Cases

Cara Implement Web Scraping dengan Claude Code

Pelajari cara implement web scraping menggunakan Claude Code. Dilengkapi contoh kode praktis dan panduan langkah demi langkah.

Webスクレイピング dengan Claude Code: efisiensi

Webスクレイピング 、データ収集やpemantauan、競合分析 dll. pemanfaatanさ技術.Claude Code 使えば、HTML解析 dari データ整形ま 一貫 スクレイピングscript waktu singkat pembangunan bisa dilakukan.

Cheerioで静的halamanをスクレイピング

JavaScriptrendering 不要なhalaman Cheerio 最適.

> Cheerio dengan ニュースサイト artikelタイトル dan リンク pengambilanするscript buatkan.
> リトライ機能 dan レート制限 juga 入れて。
import * as cheerio from "cheerio";

interface Article {
  title: string;
  url: string;
  date?: string;
}

async function fetchWithRetry(
  url: string,
  retries = 3,
  delay = 1000
): Promise<string> {
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch(url, {
        headers: {
          "User-Agent": "Mozilla/5.0 (compatible; MyBot/1.0)",
        },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return await res.text();
    } catch (error) {
      if (i === retries - 1) throw error;
      console.log(`リトライ ${i + 1}/${retries}...`);
      await new Promise((r) => setTimeout(r, delay * (i + 1)));
    }
  }
  throw new Error("Unreachable");
}

async function scrapeArticles(url: string): Promise<Article[]> {
  const html = await fetchWithRetry(url);
  const $ = cheerio.load(html);
  const articles: Article[] = [];

  $("article, .article, .post").each((_, element) => {
    const titleEl = $(element).find("h2 a, h3 a, .title a").first();
    const title = titleEl.text().trim();
    const href = titleEl.attr("href");
    const date = $(element).find("time, .date").first().text().trim();

    if (title && href) {
      articles.push({
        title,
        url: new URL(href, url).toString(),
        date: date || undefined,
      });
    }
  });

  return articles;
}

Puppeteerで動的halamanをスクレイピング

SPAやJavaScript 描画さhalaman Puppeteer 使い.

import puppeteer from "puppeteer";

interface ProductData {
  name: string;
  price: number;
  rating: number;
  imageUrl: string;
}

async function scrapeDynamicPage(url: string): Promise<ProductData[]> {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();

  // 不要なリソース ブロック cepat化
  await page.setRequestInterception(true);
  page.on("request", (req) => {
    const type = req.resourceType();
    if (["image", "stylesheet", "font"].includes(type)) {
      req.abort();
    } else {
      req.continue();
    }
  });

  await page.goto(url, { waitUntil: "networkidle2" });

  // 無限scroll 全データ 読み込む
  let previousHeight = 0;
  while (true) {
    const currentHeight = await page.evaluate(() => document.body.scrollHeight);
    if (currentHeight === previousHeight) break;
    previousHeight = currentHeight;
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await new Promise((r) => setTimeout(r, 1500));
  }

  const products = await page.evaluate(() => {
    const items = document.querySelectorAll(".product-card");
    return Array.from(items).map((item) => ({
      name: item.querySelector(".product-name")?.textContent?.trim() || "",
      price: parseFloat(
        item.querySelector(".price")?.textContent?.replace(/[^0-9.]/g, "") || "0"
      ),
      rating: parseFloat(
        item.querySelector(".rating")?.getAttribute("data-value") || "0"
      ),
      imageUrl: item.querySelector("img")?.getAttribute("src") || "",
    }));
  });

  await browser.close();
  return products;
}

penyimpananとstruktur化 データ

pengambilan データ JSON、CSV形式 penyimpanan.

import fs from "fs/promises";

async function saveAsJson(data: unknown[], filePath: string) {
  await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
  console.log(`${filePath} ${(data as any[]).length}件 penyimpananしま`);
}

function toCsvString(data: Record<string, unknown>[]): string {
  if (data.length === 0) return "";

  const headers = Object.keys(data[0]);
  const rows = data.map((row) =>
    headers.map((h) => {
      const val = String(row[h] ?? "");
      return val.includes(",") || val.includes('"')
        ? `"${val.replace(/"/g, '""')}"`
        : val;
    }).join(",")
  );

  return [headers.join(","), ...rows].join("\n");
}

async function saveAsCsv(data: Record<string, unknown>[], filePath: string) {
  const csv = toCsvString(data);
  await fs.writeFile(filePath, csv, "utf-8");
  console.log(`${filePath} penyimpananしま`);
}

定期実行とスケジューリング

import cron from "node-cron";

function startScheduledScraping() {
  // 毎日9時 実行
  cron.schedule("0 9 * * *", async () => {
    console.log(`[${new Date().toISOString()}] スクレイピングmulai`);

    try {
      const articles = await scrapeArticles("https://example.com/news");
      const timestamp = new Date().toISOString().split("T")[0];
      await saveAsJson(articles, `./data/articles-${timestamp}.json`);
    } catch (error) {
      console.error("スクレイピングerror:", error);
    }
  });

  console.log("スケジュールpengaturanselesai(毎日9:00実行)");
}

倫理的な配慮

Webスクレイピング 行う際 、berikut 点 注意 .

  • robots.txt konfirmasiし、クローリング 許可されてかkonfirmasi
  • request間隔 tepat 設けてserver 負荷 かけ tidak
  • pemanfaatan規約 konfirmasiし、スクレイピング 禁止されてい tidakかkonfirmasi
  • pengambilan データ 著作権 dan pemanfaatan目的 考慮

Markdown形式 データ 加工 metode Markdownpemrosesan・konversi silakan lihat.CLItools sebagai pembangunan 場合 CLItoolspengembangan juga ご覧.

Summary

Dengan Claude Code, 静的・動的halaman スクレイピング、データ整形、定期実行ま 含めたスクレイピングsistem waktu singkat pembangunan bisa dilakukan.セレクタ penentuanやデータkonversi juga 自然言語 指示 だけ.

Untuk detail lebih lanjut, lihat Dokumentasi Resmi Claude Code.

#Claude Code #web scraping #Puppeteer #Cheerio #データ収集