The Web Scraping Engineer extracts structured data from websites at scale. Start with the simplest tool that works: if a site returns static HTML, use Cheerio (fast, no browser needed). Only reach for Playwright if JavaScript rendering is required. Always check for an API first - many sites have undocumented REST or GraphQL endpoints that are more reliable than scraping the DOM.
Static HTML Scraping with Cheerio
import * as cheerio from 'cheerio';
async function scrapeProductList(url: string) {
const res = await fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; research-bot/1.0)',
'Accept-Language': 'en-US,en;q=0.9',
},
});
if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
const html = await res.text();
const $ = cheerio.load(html);
const products: { name: string; price: string; url: string }[] = [];
$('[data-testid="product-card"]').each((_, el) => {
const card = $(el);
products.push({
name: card.find('h2').text().trim(),
price: card.find('[data-price]').attr('data-price') ?? '',
url: new URL(card.find('a').attr('href') ?? '', url).href,
});
});
return products;
}
JavaScript-Rendered Sites with Playwright
import { chromium } from 'playwright';
async function scrapeWithPlaywright(url: string) {
const browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const context = await browser.newContext({
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
locale: 'en-US',
viewport: { width: 1280, height: 800 },
// Block images and fonts - 3x faster
serviceWorkers: 'block',
});
const page = await context.newPage();
await page.route('**/*.{png,jpg,jpeg,gif,svg,woff,woff2}', r => r.abort());
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
// Wait for actual content to appear, not arbitrary time
await page.waitForSelector('[data-testid="product-card"]', { timeout: 10_000 });
// Extract via page.evaluate - runs in browser context
const products = await page.evaluate(() => {
return Array.from(document.querySelectorAll('[data-testid="product-card"]')).map(el => ({
name: el.querySelector('h2')?.textContent?.trim() ?? '',
price: (el.querySelector('[data-price]') as HTMLElement)?.dataset.price ?? '',
}));
});
await browser.close();
return products;
}
Crawl Etiquette and Rate Limiting
// Polite crawl: respect robots.txt, add delays, use cache
import robotsParser from 'robots-parser';
class PoliteCrawler {
private delay = 2000; // 2 seconds between requests to same domain
private lastRequestTime: Record<string, number> = {};
async canFetch(url: string): Promise<boolean> {
const { origin } = new URL(url);
const robotsTxt = await fetch(`${origin}/robots.txt`).then(r => r.text()).catch(() => '');
const robots = robotsParser(`${origin}/robots.txt`, robotsTxt);
return robots.isAllowed(url, 'research-bot') ?? true;
}
async fetch(url: string): Promise<Response> {
const { hostname } = new URL(url);
const now = Date.now();
const last = this.lastRequestTime[hostname] ?? 0;
const wait = Math.max(0, this.delay - (now - last));
if (wait > 0) await new Promise(r => setTimeout(r, wait));
this.lastRequestTime[hostname] = Date.now();
return fetch(url);
}
}