Claude Code के साथ Implement Web Scraping कैसे करें
Claude Code का उपयोग करके implement web scraping सीखें। Practical code examples और step-by-step guidance शामिल है।
Webスクレイピングको Claude Code से Efficient बनाएं
Webスクレイピングは、data収集や監視、競合分析 आदिにutilizationされる技術 है।Claude Code का उपयोग करके、HTML解析 सेdata整形 तक一貫したスクレイピングスクリプトをकम समय मेंbuild किया जा सकता है。
Cheerioで静的pageをスクレイピング
JavaScriptレンダリングが不要なpageにはCheerioが最適 है।
> Cheerioでニュースサイトの記事タイトルとlink fetchするスクリプトを作って。
> リトライfeaturesとレート制限も入れて。
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で動的pageをスクレイピング
SPAやJavaScriptで描画されるpageにはPuppeteer use करके है।
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();
// 不要なリソースをブロックしてfast化
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で全dataを読み込む
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;
}
dataの保存と構造化
fetchしたdataをJSON、CSV形式で保存し है।
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}件を保存しました`);
}
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} に保存しました`);
}
定期実行とスケジューリング
import cron from "node-cron";
function startScheduledScraping() {
// 毎日9時に実行
cron.schedule("0 9 * * *", async () => {
console.log(`[${new Date().toISOString()}] スクレイピング開始`);
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("schedulesettings完了(毎日9:00実行)");
}
倫理的な配慮
Webスクレイピングをकरना際は、निम्नलिखितの点にध्यानして करें।
- robots.txt confirmし、クローリングが許可されているかconfirmする
- requestबीच隔をappropriateに設けてserverに負荷をかけない
- 利用規約 confirmし、スクレイピングが禁止されていないかconfirmする
- fetchしたdataの著作権と利用目的を考慮する
Markdown形式でdataを加工する方法はMarkdownprocessing・変換をदेखें。CLIツール के रूप मेंbuildするcase मेंCLIツールdevelopmentもदेखें。
Summary
Claude Code का उपयोग करके、静的・動的pageのスクレイピング、data整形、定期実行 तक शामिलスクレイピングシステムをकम समय मेंbuild किया जा सकता है。セレクタの指定やdata変換も自然言語で指示するだけ है।
विस्तार से जानने के लिएClaude Codeofficial documentationをदेखें。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।