Skip to content
jshacks.dev
Node.js

How to Scrape a Web Page With Node.js

Scrape a web page with Node.js using built-in fetch and cheerio: download HTML, select elements, extract text and links, and stay polite with delays.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Node.js, GraphQL, Swagger and NGINX logos.

Scraping a page is two separate jobs wearing one name. The first is getting the HTML, which Node.js can do on its own with the global fetch. The second is pulling the parts you want out of that HTML, and for that you want a parser that understands selectors instead of a pile of regular expressions that breaks the first time a site adds an attribute. This post uses Node.js 26 with its built-in fetch and cheerio 1.1 to download a page, select elements, extract text, links and tables, and then covers the part people skip until they are blocked: robots rules, headers, rate limits and what to do when the content only appears after JavaScript runs. Read the target site's terms before you scrape anything you do not own.

Fetching the HTML

fetch has been global since Node.js 18, so there is nothing to install for this half. A response has a status, headers and a body you can read as text.

fetch-page.mjsJavaScript
const response = await fetch("https://example.com/", {
  headers: { "User-Agent": "my-research-bot/1.0 (contact: [email protected])" },
});

console.log(response.status);
console.log(response.headers.get("content-type"));

const html = await response.text();
console.log(html.includes("<h1>Example Domain</h1>"));
Text
200
text/html
true

The content-type header may carry a charset after the media type on other sites, such as text/html; charset=UTF-8, so match on the start of the value and not on equality. Two habits are worth building from the first request. Check response.ok before you parse, because a 404 page is still HTML and your selectors will happily return nothing, which looks like a bug in your selectors and is not. And send an honest User-Agent that says who you are and how to reach you. A default or fake browser string is the quickest way to be blocked, and a descriptive one gets you a phone call instead of a ban when your script misbehaves.

Parsing with cheerio

cheerio implements a jQuery-style API over a parsed HTML tree on the server. It does not run scripts or lay anything out, so it is fast and uses little memory. Load a string, get back a function, and select with CSS selectors.

Shell
npm install cheerio

To keep the output exact and independent of any real site, the next examples parse a fixed HTML string. The code is the same whether the string came from fetch or from a literal.

parse-basic.mjsJavaScript
import * as cheerio from "cheerio";

const html = `
<html>
  <body>
    <h1 class="title">Weekly Deals</h1>
    <ul id="products">
      <li class="item" data-id="11"><a href="/p/keyboard">Keyboard</a> <span class="price">$49.50</span></li>
      <li class="item" data-id="12"><a href="/p/monitor">Monitor</a> <span class="price">$219.00</span></li>
      <li class="item sold-out" data-id="13"><a href="/p/cable">Cable</a> <span class="price">$4.25</span></li>
    </ul>
  </body>
</html>`;

const $ = cheerio.load(html);

console.log($("h1.title").text());
console.log($("#products .item").length);
console.log($("#products .item").first().attr("data-id"));
Text
Weekly Deals
3
11

$("selector") returns a collection. .text() joins the text of the whole collection, .attr(name) reads from the first element, and .length counts matches. A selector that matches nothing returns an empty collection, not an error, and .text() on it returns an empty string. That quietness is convenient and hides mistakes, so log the length of any collection you expect to be non-empty.

Extracting a list of records

The usual goal is an array of objects. Use .map() then .get() to turn the collection into a plain array, or loop with .each().

extract-records.mjsJavaScript
import * as cheerio from "cheerio";

const html = `
<ul id="products">
  <li class="item" data-id="11"><a href="/p/keyboard">Keyboard</a> <span class="price">$49.50</span></li>
  <li class="item" data-id="12"><a href="/p/monitor">Monitor</a> <span class="price">$219.00</span></li>
  <li class="item sold-out" data-id="13"><a href="/p/cable">Cable</a> <span class="price">$4.25</span></li>
</ul>`;

const $ = cheerio.load(html);

const products = $("#products .item")
  .map((_, el) => {
    const item = $(el);
    return {
      id: Number(item.attr("data-id")),
      name: item.find("a").text(),
      url: item.find("a").attr("href"),
      price: Number(item.find(".price").text().replace("$", "")),
      soldOut: item.hasClass("sold-out"),
    };
  })
  .get();

console.log(products);
Text
[
  {
    id: 11,
    name: 'Keyboard',
    url: '/p/keyboard',
    price: 49.5,
    soldOut: false
  },
  {
    id: 12,
    name: 'Monitor',
    url: '/p/monitor',
    price: 219,
    soldOut: false
  },
  { id: 13, name: 'Cable', url: '/p/cable', price: 4.25, soldOut: true }
]

Notice that the callback receives a raw element, and you wrap it with $(el) to get the query methods. Notice too that url is relative. Resolve links against the page address with the URL class before you follow them.

resolve-links.mjsJavaScript
const base = "https://shop.example.com/deals/week-47";

for (const href of ["/p/keyboard", "../deals/week-48", "https://other.example.org/x"]) {
  console.log(new URL(href, base).href);
}
Text
https://shop.example.com/p/keyboard
https://shop.example.com/deals/week-48
https://other.example.org/x

The second result shows why you should not concatenate strings: .. climbs one path segment and the URL constructor does the arithmetic for you.

Tables and attributes

Tables are common and awkward. Select each row, then each cell.

table.mjsJavaScript
import * as cheerio from "cheerio";

const html = `
<table>
  <tr><th>City</th><th>Population</th></tr>
  <tr><td>Oslo</td><td>709,000</td></tr>
  <tr><td>Bergen</td><td>289,000</td></tr>
</table>`;

const $ = cheerio.load(html);
const rows = $("tr")
  .slice(1)
  .map((_, tr) => {
    const [city, pop] = $(tr)
      .find("td")
      .map((__, td) => $(td).text().trim())
      .get();
    return { city, population: Number(pop.replaceAll(",", "")) };
  })
  .get();

console.log(rows);
Text
[
  { city: 'Oslo', population: 709000 },
  { city: 'Bergen', population: 289000 }
]

.slice(1) drops the header row. The trim() matters because real pages are full of whitespace and line breaks inside cells, and Number(" 709,000 ") is NaN until you clean the text.

Be polite, or be blocked

A scraper that works on ten pages and hammers ten thousand is a different animal. A few rules keep you out of trouble.

Read /robots.txt for the host and honor the paths it disallows for your user agent. It is a convention, not a lock, and ignoring it is both rude and a reason to be banned. Add a delay between requests, and a small concurrency cap, so you never look like an attack. Send a conditional request when you revisit a page, using the ETag or Last-Modified the server gave you, because a 304 response costs the server almost nothing. And back off on 429 and 503 responses: honor a Retry-After header if there is one, and otherwise wait longer after each failure.

polite.mjsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function politeGet(url, attempts = 3) {
  for (let i = 0; i < attempts; i += 1) {
    const res = await fetch(url, {
      headers: { "User-Agent": "my-research-bot/1.0 (contact: [email protected])" },
    });
    if (res.status === 429 || res.status === 503) {
      const wait = Number(res.headers.get("retry-after")) || 2 ** i;
      console.log(`retry in ${wait}s`);
      await sleep(wait * 1000);
      continue;
    }
    return res;
  }
  throw new Error(`gave up on ${url}`);
}

const urls = ["https://example.com/", "https://example.com/"];
for (const url of urls) {
  const res = await politeGet(url);
  console.log(res.status);
  await sleep(1000);
}
Text
200
200

The loop is serial on purpose. One request per second is slow, and it is also what a considerate client looks like. If a site offers an API or a data export, use that instead: it is more stable than HTML, and it is the answer the owner would prefer you choose.

When the data is not in the HTML

Many pages ship a near-empty document and fill it with JavaScript after load. fetch plus cheerio sees only the empty shell. Before you reach for a headless browser, open the browser's network panel and look for the JSON request the page makes. Calling that endpoint directly, with the same headers, is lighter and far more stable than parsing rendered markup. Some pages also embed their data in a <script type="application/json"> or application/ld+json tag, which you can select with cheerio and parse with JSON.parse.

embedded-json.mjsJavaScript
import * as cheerio from "cheerio";

const html = `<script type="application/ld+json">{"@type":"Product","name":"Monitor","offers":{"price":"219.00"}}</script>`;
const $ = cheerio.load(html);
const data = JSON.parse($('script[type="application/ld+json"]').text());

console.log(data.name, data.offers.price);
Text
Monitor 219.00

Only when the content truly does not exist until scripts run should you move to puppeteer or playwright, which drive a real browser. They cost a browser process per page, so treat them as the last step, not the first.

Where the advice stops

Selectors are brittle. A site redesign renames a class and your scraper silently returns empty arrays, so assert on what you expect (at least one item, a price that parses to a number) and fail loudly when it is wrong. Scraping is also a legal and ethical question that code cannot settle: terms of service, copyright and personal data rules differ by country and by site. Prefer official APIs, collect only what you need and do not republish what you do not have the right to. The cheerio documentation lists the full selector and traversal API.

A checklist before you run it at scale

Before you point the script at thousands of pages, walk through a short list. Fetch one page by hand and confirm the status and the content type. Print the length of every collection you select, so a changed layout shows up as a zero. Save the raw HTML of a few pages to disk while you develop, so you can fix selectors offline without sending the same request again and again, which is kinder to the site and faster for you. Write results as you go, one line per record, so a crash at page nine hundred does not lose the first eight hundred and ninety nine. Finally, record the address and the time of each fetch next to each record, because six months later you will want to know where a strange value came from and whether the page has changed since.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.