Web scraping

suggest change

Web scraping means downloading web pages with a program and pulling structured data out of their HTML. Node.js is a good fit: fetch is built in, HTML parsers are fast, and async code makes it easy to download many pages at once (and just as easy to overload a server, so the politeness rules below matter).

Task Tool
Download pages built-in fetch (Node.js 18+)
Parse static HTML with CSS selectors cheerio
Limit the number of parallel requests p-limit
Respect robots.txt robots-parser
Pages rendered by client-side JavaScript playwright (a real headless browser)

The examples are ES modules (save them as .mjs) and were run with Node.js 24, cheerio 1.2, p-limit 7.3, robots-parser 3.0 and playwright 1.64. Install them with npm install cheerio p-limit robots-parser playwright.

Before you scrape a real site: check its terms of service, prefer an official API if one exists, don't collect personal data you have no right to, and keep your request rate low. A scraper that sends hundreds of requests per second is indistinguishable from a denial-of-service attack.

A local practice site

Scraping a live site makes examples fragile (the HTML changes, the network fails), so all examples below scrape a tiny bookshop served by node:http on a random free port. It has paginated list pages, detail pages with embedded JSON-LD, a JSON API, a robots.txt, a page rendered by client-side JavaScript, and two misbehaving URLs: /flaky fails twice with HTTP 503 before succeeding and /slow takes 5 seconds to answer.

// server.mjs: a tiny bookshop to practice scraping on
import { createServer } from 'node:http';

const books = [
  { id: 1, title: 'The Pragmatic Programmer', author: 'Hunt & Thomas', price: 39.95, rating: 5 },
  { id: 2, title: 'Eloquent JavaScript', author: 'Marijn Haverbeke', price: 29.0, rating: 4 },
  { id: 3, title: 'Node.js Design Patterns', author: 'Casciaro & Mammino', price: 44.99, rating: 5 },
  { id: 4, title: 'You Don’t Know JS', author: 'Kyle Simpson', price: 0, rating: 4 },
  { id: 5, title: 'Refactoring', author: 'Martin Fowler', price: 47.5, rating: 3 },
];
const PER_PAGE = 2;
const pages = Math.ceil(books.length / PER_PAGE);
let flakyHits = 0;
export const stats = { requests: 0, active: 0, maxActive: 0, userAgents: new Set() };

const layout = (title, body) => `<!doctype html>
<html><head><meta charset="utf-8"><title>${title} | Tiny Bookshop</title></head>
<body><nav><a href="/">Home</a> <a href="/admin">Admin</a></nav>${body}</body></html>`;

function listPage(page) {
  const items = books.slice((page - 1) * PER_PAGE, page * PER_PAGE).map((b) => `
    <article class="book" data-id="${b.id}">
      <h2><a href="book/${b.id}">${b.title}</a></h2>
      <p class="author">by ${b.author}</p>
      <p class="price">${b.price ? '$' + b.price.toFixed(2) : 'Free'}</p>
      <p class="rating" title="${b.rating} out of 5">${'★'.repeat(b.rating)}</p>
    </article>`).join('');
  const next = page < pages ? `<a rel="next" href="/books?page=${page + 1}">Next</a>` : '';
  return layout(`Books, page ${page}`, `<h1>Books</h1>${items}<footer>${next}</footer>`);
}

function detailPage(b) {
  const ld = { '@context': 'https://schema.org', '@type': 'Book', name: b.title,
    author: { '@type': 'Person', name: b.author }, isbn: `978-0-00-00000${b.id}-0`,
    offers: { '@type': 'Offer', price: b.price.toFixed(2), priceCurrency: 'USD' } };
  return layout(b.title, `<h1>${b.title}</h1><p class="author">by ${b.author}</p>
    <script type="application/ld+json">${JSON.stringify(ld)}</script>`);
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function handle(req, res) {
  const url = new URL(req.url, 'http://localhost');
  const send = (status, type, body, headers = {}) => {
    res.writeHead(status, { 'content-type': type, ...headers });
    res.end(body);
  };
  await sleep(50); // pretend to do some work
  if (url.pathname === '/robots.txt') {
    return send(200, 'text/plain', 'User-agent: *\nDisallow: /admin\nCrawl-delay: 1\n');
  }
  if (url.pathname === '/' || url.pathname === '/books') {
    const page = Number(url.searchParams.get('page') ?? 1);
    if (page < 1 || page > pages) return send(404, 'text/html', layout('Not found', '<h1>404</h1>'));
    return send(200, 'text/html; charset=utf-8', listPage(page));
  }
  const m = url.pathname.match(/^\/book\/(\d+)$/);
  if (m) {
    const b = books.find((x) => x.id === Number(m[1]));
    if (b) return send(200, 'text/html; charset=utf-8', detailPage(b));
  }
  if (url.pathname === '/api/books') {
    return send(200, 'application/json', JSON.stringify({ total: books.length, books }));
  }
  if (url.pathname === '/app') { // client-side rendered page
    return send(200, 'text/html; charset=utf-8', layout('App', `<ul id="list">Loading...</ul>
      <script>fetch('/api/books').then((r) => r.json()).then(({ books }) => {
        document.querySelector('#list').innerHTML =
          books.map((b) => '<li class="book">' + b.title + '</li>').join('');
      });</script>`));
  }
  if (url.pathname === '/flaky') {
    flakyHits++;
    if (flakyHits % 3 !== 0) return send(503, 'text/plain', 'busy', { 'retry-after': '1' });
    return send(200, 'text/plain', 'finally worked');
  }
  if (url.pathname === '/slow') {
    await sleep(5000);
    return send(200, 'text/plain', 'sorry for the wait');
  }
  send(404, 'text/html', layout('Not found', '<h1>404</h1>'));
}

export function startServer() {
  const server = createServer(async (req, res) => {
    stats.requests++;
    stats.userAgents.add(req.headers['user-agent']);
    stats.active++;
    stats.maxActive = Math.max(stats.maxActive, stats.active);
    try {
      await handle(req, res);
    } finally {
      stats.active--;
    }
  });
  return new Promise((resolve) => {
    server.listen(0, '127.0.0.1', () => {
      const base = `http://127.0.0.1:${server.address().port}`;
      resolve({ base, close: () => server.close() });
    });
  });
}

Each example starts the server, scrapes it and closes it. Because the port changes on every run, the examples print paths rather than full URLs. To scrape a real site, replace base with its address.

Downloading a page

fetch returns a Response as soon as the headers arrive. Check the status, then read the body with text() (or json() for an API):

import { startServer } from './server.mjs';
const { base, close } = await startServer();

const res = await fetch(`${base}/`);
console.log(res.status, res.statusText);
console.log(res.headers.get('content-type'));
const html = await res.text();
console.log(html.length, 'chars');
console.log(html.slice(0, 120));
close();
200 OK
text/html; charset=utf-8
745 chars
<!doctype html>
<html><head><meta charset="utf-8"><title>Books, page 1 | Tiny Bookshop</title></head>
<body><nav><a href

fetch does not throw on HTTP errors such as 404 or 500; it only throws when the request itself fails (DNS error, refused connection, timeout). Always check res.ok or res.status. See http client for the lower-level node:http API.

Extracting data with cheerio

cheerio.load() parses HTML into a tree you query with CSS selectors and a jQuery-like API. It doesn't run JavaScript or render anything, which makes it fast. Parsing HTML covers cheerio and JSDOM in more detail; here is what a typical extraction looks like:

import * as cheerio from 'cheerio';
import { startServer } from './server.mjs';
const { base, close } = await startServer();

const pageUrl = `${base}/`;
const html = await (await fetch(pageUrl)).text();
const $ = cheerio.load(html);

console.log('title:', $('title').text());

const books = $('article.book').map((_, el) => {
  const $el = $(el);
  const priceText = $el.find('.price').text().trim();
  return {
    id: Number($el.attr('data-id')),
    title: $el.find('h2').text().trim(),
    author: $el.find('.author').text().replace(/^by\s+/, ''),
    price: priceText === 'Free' ? 0 : Number(priceText.replace(/[^0-9.]/g, '')),
    rating: $el.find('.rating').text().length,
    url: new URL($el.find('h2 a').attr('href'), pageUrl).pathname,
  };
}).get();
console.log(books);

const next = $('a[rel="next"]').attr('href');
console.log('next page:', next);
close();
title: Books, page 1 | Tiny Bookshop
[
  {
    id: 1,
    title: 'The Pragmatic Programmer',
    author: 'Hunt & Thomas',
    price: 39.95,
    rating: 5,
    url: '/book/1'
  },
  {
    id: 2,
    title: 'Eloquent JavaScript',
    author: 'Marijn Haverbeke',
    price: 29,
    rating: 4,
    url: '/book/2'
  }
]
next page: /books?page=2

Things to note:

Cheerio 1.x also has fromURL(), which downloads and parses in one step, and extract(), which describes the data you want as an object:

import * as cheerio from 'cheerio';
import { startServer } from './server.mjs';
const { base, close } = await startServer();

const $ = await cheerio.fromURL(`${base}/books?page=2`);
console.log($('h2').map((_, el) => $(el).text()).get());
const data = $.extract({
  titles: ['article.book h2'],
  next: { selector: 'a[rel="next"]', value: 'href' },
});
console.log(data);
close();
[ 'Node.js Design Patterns', 'You Don’t Know JS' ]
{
  titles: [ 'Node.js Design Patterns', 'You Don’t Know JS' ],
  next: '/books?page=3'
}

fromURL() is handy for quick scripts. For real scrapers you'll want control over headers, timeouts and retries, which the next section adds.

A robust, polite fetch

A production scraper needs a few things plain fetch doesn't give you:

// fetchpage.mjs: a polite, robust fetch for scrapers
const USER_AGENT = 'TinyBot/1.0 (+https://example.com/bot; bot@example.com)';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function fetchPage(url, { retries = 3, timeoutMs = 10_000 } = {}) {
  for (let attempt = 0; ; attempt++) {
    let res;
    try {
      res = await fetch(url, {
        headers: { 'user-agent': USER_AGENT, accept: 'text/html,application/json' },
        signal: AbortSignal.timeout(timeoutMs),
      });
    } catch (err) {
      // network error or timeout
      if (attempt >= retries) throw err;
      console.log(`  ${err.name} on ${new URL(url).pathname}, retrying`);
      await sleep(500 * 2 ** attempt);
      continue;
    }
    if (res.ok) return res;

    const retryable = res.status === 429 || res.status >= 500;
    if (!retryable || attempt >= retries) {
      throw new Error(`HTTP ${res.status} for ${url}`);
    }
    await res.body?.cancel(); // free the connection
    const retryAfter = Number(res.headers.get('retry-after'));
    const delay = retryAfter > 0 ? retryAfter * 1000 : 500 * 2 ** attempt;
    console.log(`  HTTP ${res.status} on ${new URL(url).pathname}, retry in ${delay} ms`);
    await sleep(delay);
  }
}

Trying it on the misbehaving URLs:

import { startServer } from './server.mjs';
import { fetchPage } from './fetchpage.mjs';
const { base, close } = await startServer();

const res = await fetchPage(`${base}/flaky`);
console.log('flaky:', await res.text());

try {
  await fetchPage(`${base}/slow`, { timeoutMs: 1000, retries: 1 });
} catch (err) {
  console.log('slow:', err.name, '-', err.message);
}

try {
  await fetchPage(`${base}/no-such-page`);
} catch (err) {
  console.log('missing:', err.message.replace(base, ''));
}
close();
  HTTP 503 on /flaky, retry in 1000 ms
  HTTP 503 on /flaky, retry in 1000 ms
flaky: finally worked
  TimeoutError on /slow, retrying
slow: TimeoutError - The operation was aborted due to timeout
missing: HTTP 404 for /no-such-page

When you give up on a response without reading it, cancel its body (res.body.cancel()). Otherwise the underlying connection stays busy until the garbage collector cleans it up.

Following pagination

List pages usually link to the next page. An async generator that follows rel="next" links keeps the paging logic separate from the extraction logic. Always cap the number of pages, in case a site links pages in a loop:

import * as cheerio from 'cheerio';
import { startServer } from './server.mjs';
import { fetchPage } from './fetchpage.mjs';
const { base, close } = await startServer();

async function* listPages(startUrl, maxPages = 50) {
  let url = startUrl;
  for (let n = 0; url && n < maxPages; n++) {
    const $ = cheerio.load(await (await fetchPage(url)).text());
    yield { url, $ };
    const next = $('a[rel="next"]').attr('href');
    url = next ? new URL(next, url).href : null;
  }
}

const links = [];
for await (const { url, $ } of listPages(`${base}/`)) {
  const found = $('article.book h2 a').map((_, a) => new URL($(a).attr('href'), url).href).get();
  console.log(new URL(url).pathname + new URL(url).search, '->', found.length, 'books');
  links.push(...found);
}
console.log(links.map((u) => new URL(u).pathname));
close();
/ -> 2 books
/books?page=2 -> 2 books
/books?page=3 -> 1 books
[ '/book/1', '/book/2', '/book/3', '/book/4', '/book/5' ]

If there is no "next" link but the URL has a page number, loop over ?page=1, ?page=2, ... and stop at the first 404 or empty page.

Detail pages in parallel, with a limit

Promise.all(urls.map(fetch)) would start every request at once. With thousands of URLs that gets you rate-limited or banned, and it can exhaust sockets and memory on your side too. p-limit caps how many tasks run at the same time.

Many sites embed machine-readable data as JSON-LD (<script type="application/ld+json">) for search engines. When it's there, parse it instead of scraping the visible markup: it's cleaner, typed, and changes less often than the page design.

import * as cheerio from 'cheerio';
import pLimit from 'p-limit';
import { startServer, stats } from './server.mjs';
import { fetchPage } from './fetchpage.mjs';
const { base, close } = await startServer();

function parseBook($) {
  const ld = $('script[type="application/ld+json"]')
    .map((_, el) => JSON.parse($(el).text())).get()
    .find((d) => d['@type'] === 'Book');
  return {
    title: ld.name,
    author: ld.author.name,
    isbn: ld.isbn,
    price: Number(ld.offers.price),
  };
}

const urls = [1, 2, 3, 4, 5].map((id) => `${base}/book/${id}`);
const limit = pLimit(2); // at most 2 requests in flight

const books = await Promise.all(urls.map((url) => limit(async () => {
  const $ = cheerio.load(await (await fetchPage(url)).text());
  return parseBook($);
})));
console.table(books);
console.log('max concurrent requests seen by server:', stats.maxActive);
close();
┌─────────┬────────────────────────────┬──────────────────────┬─────────────────────┬───────┐
│ (index) │ title                      │ author               │ isbn                │ price │
├─────────┼────────────────────────────┼──────────────────────┼─────────────────────┼───────┤
│ 0       │ 'The Pragmatic Programmer' │ 'Hunt & Thomas'      │ '978-0-00-000001-0' │ 39.95 │
│ 1       │ 'Eloquent JavaScript'      │ 'Marijn Haverbeke'   │ '978-0-00-000002-0' │ 29    │
│ 2       │ 'Node.js Design Patterns'  │ 'Casciaro & Mammino' │ '978-0-00-000003-0' │ 44.99 │
│ 3       │ 'You Don’t Know JS'        │ 'Kyle Simpson'       │ '978-0-00-000004-0' │ 0     │
│ 4       │ 'Refactoring'              │ 'Martin Fowler'      │ '978-0-00-000005-0' │ 47.5  │
└─────────┴────────────────────────────┴──────────────────────┴─────────────────────┴───────┘
max concurrent requests seen by server: 2

Promise.all keeps results in the same order as urls, no matter which request finishes first. If one task throws, Promise.all rejects; use Promise.allSettled when you'd rather collect partial results and log the failures.

A concurrency limit alone doesn't bound the request rate: with fast responses, 2 parallel requests can still mean dozens per second. For small sites, use one request at a time plus a delay, as the crawler below does.

Respecting robots.txt

robots.txt tells bots which paths they shouldn't visit and, sometimes, how long to wait between requests. It isn't enforced by anything, but well-behaved scrapers follow it:

import robotsParser from 'robots-parser';
import { startServer } from './server.mjs';
const { base, close } = await startServer();

const robotsUrl = new URL('/robots.txt', base).href;
const res = await fetch(robotsUrl);
const robots = robotsParser(robotsUrl, res.ok ? await res.text() : '');

for (const path of ['/', '/book/3', '/admin', '/admin/users']) {
  console.log(path.padEnd(12), robots.isAllowed(new URL(path, base).href, 'TinyBot') ? 'allowed' : 'disallowed');
}
console.log('crawl delay:', robots.getCrawlDelay('TinyBot'), 'seconds');
close();
/            allowed
/book/3      allowed
/admin       disallowed
/admin/users disallowed
crawl delay: 1 seconds

A missing robots.txt (404) means everything is allowed, which is why the example passes an empty string in that case.

A small crawler

A crawler combines everything: start from one URL, extract links, normalize them, keep only links on the same site, skip pages it has already seen or that robots.txt disallows, and wait between requests. A queue makes it a breadth-first crawl:

import * as cheerio from 'cheerio';
import robotsParser from 'robots-parser';
import { startServer, stats } from './server.mjs';
import { fetchPage } from './fetchpage.mjs';
const { base, close } = await startServer();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function normalize(href, from) {
  let url;
  try {
    url = new URL(href, from);
  } catch {
    return null; // not a valid URL
  }
  if (!['http:', 'https:'].includes(url.protocol)) return null; // mailto:, javascript:
  url.hash = '';
  return url.href;
}

async function crawl(startUrl, { maxPages = 100 } = {}) {
  const origin = new URL(startUrl).origin;
  const robotsUrl = `${origin}/robots.txt`;
  const robotsTxt = await fetchPage(robotsUrl).then((r) => r.text(), () => '');
  const robots = robotsParser(robotsUrl, robotsTxt);
  const delayMs = (robots.getCrawlDelay('TinyBot') ?? 0.5) * 1000;

  const queue = [startUrl];
  const seen = new Set(queue);
  const results = [];

  while (queue.length > 0 && results.length < maxPages) {
    const url = queue.shift();
    if (!robots.isAllowed(url, 'TinyBot')) {
      console.log('skip (robots.txt)', new URL(url).pathname);
      continue;
    }
    let res;
    try {
      res = await fetchPage(url, { retries: 1 });
    } catch (err) {
      console.log('failed:', err.message);
      continue;
    }
    if (!res.headers.get('content-type')?.startsWith('text/html')) continue;

    const $ = cheerio.load(await res.text());
    results.push({ path: new URL(url).pathname + new URL(url).search, title: $('h1').first().text() });

    $('a[href]').each((_, a) => {
      const link = normalize($(a).attr('href'), url);
      if (link && new URL(link).origin === origin && !seen.has(link)) {
        seen.add(link);
        queue.push(link);
      }
    });
    await sleep(delayMs);
  }
  return results;
}

const pages = await crawl(`${base}/`);
console.table(pages);
console.log('requests:', stats.requests, 'user agents:', [...stats.userAgents]);
close();
skip (robots.txt) /admin
┌─────────┬─────────────────┬────────────────────────────┐
│ (index) │ path            │ title                      │
├─────────┼─────────────────┼────────────────────────────┤
│ 0       │ '/'             │ 'Books'                    │
│ 1       │ '/book/1'       │ 'The Pragmatic Programmer' │
│ 2       │ '/book/2'       │ 'Eloquent JavaScript'      │
│ 3       │ '/books?page=2' │ 'Books'                    │
│ 4       │ '/book/3'       │ 'Node.js Design Patterns'  │
│ 5       │ '/book/4'       │ 'You Don’t Know JS'        │
│ 6       │ '/books?page=3' │ 'Books'                    │
│ 7       │ '/book/5'       │ 'Refactoring'              │
└─────────┴─────────────────┴────────────────────────────┘
requests: 9 user agents: [ 'TinyBot/1.0 (+https://example.com/bot; bot@example.com)' ]

The "Home" link appears on every page, but seen makes sure / is downloaded once. Removing the fragment (#reviews) is part of normalization because /book/1 and /book/1#reviews are the same document. Real sites need more: some treat ?sort=asc&page=2 and ?page=2&sort=asc as the same page, and calendars or faceted search can generate an endless number of URLs, which is why maxPages exists.

Look for an API first

Before writing selectors, open the browser's developer tools, go to the Network tab and reload the page. Many modern sites load their data from a JSON endpoint, and calling it directly is faster, simpler and far less fragile than parsing HTML:

import { startServer } from './server.mjs';
import { fetchPage } from './fetchpage.mjs';
const { base, close } = await startServer();

const data = await (await fetchPage(`${base}/api/books`)).json();
console.log(data.total, 'books');
console.log(data.books.filter((b) => b.rating === 5).map((b) => b.title));
close();
5 books
[ 'The Pragmatic Programmer', 'Node.js Design Patterns' ]

Pages rendered with JavaScript

Single-page applications send an almost empty HTML shell and build the content in the browser. fetch and cheerio only see the shell. For those pages, drive a real headless browser with Playwright (install the browser once with npx playwright install chromium):

import * as cheerio from 'cheerio';
import { chromium } from 'playwright';
import { startServer } from './server.mjs';
const { base, close } = await startServer();

// plain fetch only sees the HTML before JavaScript runs
const $ = cheerio.load(await (await fetch(`${base}/app`)).text());
console.log('fetch + cheerio:', $('#list').text());

const browser = await chromium.launch();
try {
  const page = await browser.newPage({ userAgent: 'TinyBot/1.0' });
  await page.goto(`${base}/app`);
  await page.locator('#list li.book').first().waitFor();
  const titles = await page.locator('#list li.book').allTextContents();
  console.log('playwright:', titles);
} finally {
  await browser.close();
}
close();
fetch + cheerio: Loading...
playwright: [
  'The Pragmatic Programmer',
  'Eloquent JavaScript',
  'Node.js Design Patterns',
  'You Don’t Know JS',
  'Refactoring'
]

Wait for the element you need (locator(...).waitFor()) rather than sleeping for a fixed time. A browser uses hundreds of megabytes of memory and is 10-100 times slower than fetch, so use it only when you have to. Often the API approach above works even for these sites, because the page itself gets its data from an API.

Saving results

Write results as you go, not at the end: a scraper that crashes after 3 hours shouldn't lose everything. JSON Lines (one JSON object per line) is perfect for this, because you can append to it and use it to skip already-scraped items after a restart. Convert to CSV at the end if someone wants to open the data in a spreadsheet:

import { appendFile, readFile, writeFile } from 'node:fs/promises';

const books = [
  { id: 1, title: 'The Pragmatic Programmer', author: 'Hunt & Thomas', price: 39.95 },
  { id: 4, title: 'You Don’t Know JS', author: 'Kyle Simpson', price: 0 },
  { id: 6, title: 'Clean Code, 2nd "Edition"', author: 'Robert C. Martin', price: 42 },
];

// JSON Lines: one record per line, safe to append as you go
await writeFile('books.jsonl', '');
for (const b of books) {
  await appendFile('books.jsonl', JSON.stringify(b) + '\n');
}

// on restart: find what's already done and skip it
const done = new Set(
  (await readFile('books.jsonl', 'utf8')).split('\n').filter(Boolean).map((l) => JSON.parse(l).id),
);
console.log('already scraped:', [...done]);

// CSV: quote every field, double embedded quotes
const csvField = (v) => `"${String(v).replaceAll('"', '""')}"`;
const columns = ['id', 'title', 'author', 'price'];
const csv = [columns, ...books.map((b) => columns.map((c) => b[c]))]
  .map((row) => row.map(csvField).join(','))
  .join('\r\n');
await writeFile('books.csv', '\ufeff' + csv); // BOM so Excel detects UTF-8
console.log(csv);
already scraped: [ 1, 4, 6 ]
"id","title","author","price"
"1","The Pragmatic Programmer","Hunt & Thomas","39.95"
"4","You Don’t Know JS","Kyle Simpson","0"
"6","Clean Code, 2nd ""Edition""","Robert C. Martin","42"

For reading CSV back, see CSV parsing.

Checklist

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents