Skip to content

Nodejs Web Scrape: Build, Render and Fix a Scraper

Learn nodejs web scrape with Axios, Cheerio and Playwright, including working code, retry rules, robots.txt checks and fixes for empty results.

Pim
Pim· Clearcote Research
14 min read

You shipped a scraper last week and it returned a few hundred rows. This morning the same script returns an empty array, the response is still 200 OK, and the only log line says done. Nothing records whether the markup changed, a consent wall appeared, or the path was never yours to fetch.

That gap between a request that succeeds and a collection you can defend is the work. A nodejs web scrape that only handles the happy path is a parsing script with a network call bolted on. The version that survives a live site gives every URL one of five states and attaches a policy decision to it, so tomorrow's run has something to compare against.

The two things worth having at the end are a scraper that fetches, escalates and retries correctly, and one log line per URL that answers what happened.

Table of Contents

Choose Fetch-and-Parse or a Real Browser First

Open the target in Chrome, open DevTools, press Ctrl+Shift+P, run "Disable JavaScript", then reload the page. If the data is still on screen, you don't need a browser. That single check saves more money than any optimisation you'll write later.

The three-question test

Run these before you install anything.

  1. Does the data appear with JavaScript off? If yes, an HTTP client plus a parser is the whole solution.
  2. Does a request in the Network tab return the data as JSON? If yes, call that endpoint directly and skip HTML entirely.
  3. Does the page need a login, a click or a scroll to reveal the rest? If yes, you need a browser with a persisted session.

Cost is what makes those answers matter. HTTP Archive measurements cited for 2024 put the median HTML document at about 18 kilobytes, while the median total page weight was approximately 2,652 kilobytes on desktop across roughly 71 requests, per BrowserBeam's scraping analysis. A rendered page therefore pulls roughly 128 times more data than the document a fetch-and-parse scraper needs, and the mobile figures land at the same ratio.

Median JavaScript payloads sit near 613 kilobytes on desktop, so script execution and the API calls behind it drive cost as much as raw page size does. Requests per second tells you very little about operating cost. Data volume, rendering, memory and whether you can block assets tell you almost everything.

What each page type costs

Page type Best approach Typical data per page Requests per page
Server-rendered listing or article Axios with Cheerio about 18 KB HTML (2024 median) 1
JavaScript-driven app or infinite scroll Playwright about 2,652 KB desktop (2024 median) about 71
Data returned by a JSON API seen in DevTools fetch the JSON directly size of the JSON response 1 per page
Login or cookie-gated content Playwright with saved session measure in DevTools measure in DevTools

A yes to question one points you at an Axios and Cheerio build. A yes to question two sends you to the third row, which is usually one request per page and the cheapest path on the list. A yes to question three means a browser with a saved profile, because the session cookie is the expensive part, not the rendering.

The fourth row is the one teams underrate. When gated content is in scope, measure the actual payload in DevTools before you budget infrastructure, since a session-backed browser page can be tiny or enormous depending on how much the app hydrates.

Rule of thumb: if the data survives JavaScript being switched off, keep the browser out of the loop.

Build Your First Scraper with Axios and Cheerio

Six steps take you from an empty folder to a JSON file you can inspect line by line.

A six-step infographic illustrating the process of building a web scraper using Node.js with Axios and Cheerio.

Create, install, request

  1. Create the project. Run mkdir scraper && cd scraper && npm init -y, then add "type": "module" to package.json. That flag marks the folder as an ES module root, so import works without renaming files or adding a build step.

  2. Install two packages. Run npm install axios cheerio. Axios gives you a timeout and a status you can branch on; Cheerio gives you jQuery-style selectors over a parsed tree with no browser attached. The stack stays this small because the registry has had years to settle: Node.js released its first version in 2009 and npm arrived in January 2010, as the Node.js project metrics record.

  3. Request, then stop on failure. Send a descriptive User-Agent, set a 10-second timeout, and throw on any status other than 200. Parsing an error page is how you end up with hundreds of rows of nulls.

    import axios from 'axios'; import * as cheerio from 'cheerio'; import fs from 'node:fs';

    const url = '';

    const res = await axios.get(url, { timeout: 10 * 1000, headers: { 'User-Agent': 'ResearchBot/2 (+)' }, });

    if (res.status !== 200) throw new Error(HTTP ${res.status});

    const $ = cheerio.load(res.data); const rows = [];

    $('.product-card').each((_, el) => { const title = $(el).find('.product-title').text().trim(); const href = $(el).find('a.product-link').attr('href'); const price = $(el).find('.price').text().trim(); if (!title || !href) return; rows.push({ title, url: new URL(href, url).toString(), price: price || null, }); });

    fs.writeFileSync('results.json', JSON.stringify(rows, null, 2)); console.log(${rows.length} rows from ${url});

  4. Anchor on one container selector. $('.product-card') should match the repeated block and nothing else. Read fields inside each card with .text() and .attr(), and resolve relative hrefs immediately with new URL(href, url) so you never debug path joins twice.

  5. Drop incomplete cards, then write the file. Skip a card with no title or link, push the rest into an array, and write it out. A half-parsed row that reaches storage looks identical to a good one three weeks later.

  6. Run it once and count. Execute node scrape.js, then compare the logged row count with the number of visible items on the page. A small difference is a selector problem. A difference of everything is a rendering problem.

What a healthy run looks like

The console count matches the visible items. Every object carries the same keys in the same order. Nothing is empty by accident, and the fields that are missing hold null rather than an empty string so you can count them in one query.

The most common first-run failure isn't a crash. It's a selector copied from a browser that executed JavaScript: DevTools showed .css-1x2y3z, the raw response contains product-card, and your parser matches nothing while reporting zero rows without an error. Check the raw HTML before you trust a class name.

Read /robots.txt by hand before that first run. Whether you're allowed to fetch a path is a separate question from whether the script works, and both belong in the same commit.

Escalate to Playwright Only When the Data Is Missing

The symptom is specific. The request returns 200 OK, the HTML looks complete, the parser runs clean, and the array is empty. That isn't an HTTP failure, it's a rendering failure, and it's the signal to escalate that URL and only that URL.

A hand using a magnifying glass to examine web development code on a laptop screen with photography equipment.

Escalate in this order

  1. Confirm the target selector is absent from the raw HTML. Save the response to disk and search it. If the class exists and only the copy is missing, you have a parser bug, not a rendering problem.
  2. Install the browser. Run npm install playwright, then npx playwright install chromium. The second command downloads the binary, and skipping it is the most common install failure.
  3. Launch headless Chromium and open the page with a timeout. waitUntil: 'domcontentloaded' stops you from waiting on every image before you can act on the page.
  4. Wait for a readiness condition, never a sleep. Three options, in order of preference:
    • An observed API response is the most stable, since the grid usually fetches JSON you can parse instead of the DOM.
    • A target selector fits listings that render cards, and it documents what "ready" means in one line.
    • A network-idle window fits pages that make several small requests, but it needs a timeout or it hangs on analytics beacons that never settle.
  5. Block images, fonts and media with page.route, aborting by resourceType. Most listings are readable without a single pixel of an image.
  6. Run the post-render checks. Look for consent overlays, login walls, paywalls, human-verification challenges, pagination truncation and load-more controls. Label a failure instead of recording an empty result.
  7. Close the browser in a finally block. A crash without cleanup leaks processes until the machine slows to a crawl.

A skeleton worth adapting, with the selector you confirmed in step one:

const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage();
  await page.route('**/*', (r) =>
    ['image', 'font', 'media'].includes(r.request().resourceType())
      ? r.abort() : r.continue());
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
  await page.waitForSelector('.product-card', { timeout: 15000 });
  const html = await page.content();
} finally {
  await browser.close();
}

Why scraped pages disagree with what users see

A 2025 study in Communication Methods and Measures compared scraped pages with pages captured during real user interaction and found the collection environment accounted for about 33.8% of discrepancies, while login and paywall conditions were responsible for 73% of the discrepancies examined. In practice that means the browser you launch, the locale you set and the session you carry are part of the data, not background noise.

The video below is a companion to these escalation steps, not a replacement for them.

Watch the video on YouTube

Reproducibility is the other half. Store the raw HTML or JSON, the selector version, the locale, the request headers, the timing and the failure reason for every page. When a parser change lands, you can recompute accuracy against stored files instead of re-crawling and hoping the site behaves the same way. If you want the full launch and context setup, the Playwright setup walkthrough covers it end to end, and our Playwright and Puppeteer SDK is a drop-in Chromium where switching an existing script means one import change and only the lines that start the browser move.

Check robots.txt and Site Rules on Every URL

A 200 response is not permission. It's proof that a server answered you. Compliance is a build step with an output you can print, not a paragraph in a README.

A checklist diagram showing the four best practices for checking robots.txt rules during web crawling.

Seven checks that produce a defensible decision

  1. Fetch /robots.txt once per host. Cache it with a timestamp and a version, then refresh it daily so a policy change reaches your next run.
  2. Parse the Disallow rules that apply to your user agent. Wildcard and group matching is fiddly, so test your parser against a few real files before trusting it.
  3. Honour Crawl-delay between requests to the same host, and treat it as a floor rather than a target.
  4. Read the terms of service and record the review date next to the policy version.
  5. Give every URL exactly one decision: allowed, delayed, excluded, or escalated for review. Write it beside the source URL, timestamp and policy version.
  6. Treat a missing robots.txt or missing terms as an open question. A site without a machine-readable rule can still have restrictions.
  7. Tag personal-data fields with a purpose and a retention period, and build the deletion path before you ingest the first record.

Most Node.js tutorials treat this as a legal disclaimer rather than an engineering feature. Illusory's compliance guide makes the useful distinction that robots.txt isn't uniformly legally binding, yet a site's stated preferences count as evidence of responsible processing, and the European Data Protection Board has stated that the absence of robots.txt does not constitute consent where personal data is involved.

"Publicly accessible" is not the same as "unrestricted for every purpose".

The same discipline runs in both directions. If you also publish pages, the crawl-budget logic behind fix pages that never get indexed is the mirror image of the rules you're reading here.

Stop rules are what make this real. An explicit prohibition ends the crawl for that URL, and an uncertain case goes to human review instead of through. A technically successful request that lacks a provenance trail is a liability with good uptime, and that's true for a small internal project as much as a commercial one.

Add Concurrency, Retries and Result States

Numbers first, because they settle the argument. A neutral Node.js benchmark on 50 pages found that concurrency 5 cut runtime from 17.8 seconds to 2.5 seconds, while raising concurrency from 5 to 10 gained only 1.1 seconds and from 10 to 20 only 0.3 seconds, per HasData's scraping benchmark write-up.

A bar chart comparing benchmark times for sequential versus concurrency 5 processing for web scraping tasks.

Concurrency has a knee, so find yours

Wrap the URL list in a queue and cap it with something like p-limit. Add per-host limits on top of the global cap, because ten workers spread over ten hosts is a different thing from ten workers hammering one. Start conservative, raise the number only when both the success rate and the wall-clock time improve, and add jitter so your requests don't march out on a metronome.

The knee is the limit. Past it, doubling workers buys a second or less and adds ban risk you can't see until the next morning.

Back off on the right failures

A withRetry helper that doubles the wait on each attempt and adds random jitter handles the transient cases: timeouts, resets and 5xx responses. What matters more is the classification around it, because retrying a permanent client error or a challenge page burns capacity and hides the problem.

Response or condition Action Result state
Network timeout or connection reset retry with exponential backoff, capped attempts success or failed after the cap
5xx server error retry with backoff and jitter success or failed after the cap
429 Too Many Requests pause the host, retry later with a longer wait success or blocked
Other 4xx responses do not retry, send to review queue missing
Login, paywall or CAPTCHA page stop for this URL, send to review queue blocked
Expected DOM marker absent do not parse, store the raw HTML partial or missing
Markup present but fields malformed parse with validation, flag the fields malformed

Five states that keep the log honest

Every record carries success, partial, blocked, missing or malformed, plus the raw response, its hash, the timestamp, the status, the redirect chain and the parser version. Report counts per state against a stated denominator, so the totals always add up to the input. Content is volatile and partly personalized, so repeated runs can produce sampling bias rather than tidy random gaps; periodic re-crawls, immutable raw storage and duplicate detection are what let you tell the difference.

Fix Empty Results, Blocks and Slow Runs

Empty results come first because they're the most common and the most misleading. An empty array isn't a network problem. Check the raw HTML before you touch the browser.

Symptom Likely cause Fix Fix time
Selector returns an empty array content loads through JavaScript or class names are generated check raw HTML, then switch to Playwright and wait for the element minutes to days
200 OK with a human-verification message challenge page mark blocked, stop retrying, send to review days (policy review)
Results stop after the first page pagination or load-more not followed follow the next link or click load-more and wait for the item count to change minutes
Duplicate rows in output no stable key hash the canonical URL plus a stable ID minutes
Run takes several minutes concurrency too low or assets not blocked raise concurrency in steps and block images and fonts minutes
Data differs between runs site updates or personalization compare stored raw HTML and parser version, re-crawl a sample days
Playwright timeout wait targets the wrong selector wait for a specific element and raise the timeout for that one domain minutes

Sort these by fix time before you start. A wrong selector, a missing header or a missing stable key costs minutes. A new readiness strategy or a policy review costs days, and that distinction decides whether you patch tonight or reschedule the job.

The 200 OK challenge page deserves its own rule, because it's the failure that poisons a dataset. Mark the URL blocked, stop retrying that path, and route it to a human. If most of your blocked rows trace back to one host, the guide to working with blocked requests covers the escalation order.

What to log for the next run

Log the URL, the final status, the redirect chain, the response hash, the selector or parser version, the timestamp, the state and one plain sentence of reason. That set lets the next run diagnose a failure without re-crawling the batch, and it turns a vague "the scraper broke" into a diff.

Run a Small Test Crawl Before You Scale

Before a large job, run 20 to 50 URLs that cover every page type you mapped. A trial that exposes nothing is cheaper than a full run that exposes everything.

  1. Build the sample deliberately, including one gated page and one JavaScript-driven page so the escalation path gets exercised.
  2. Run with the concurrency you settled on and the same retry rules the full job will use.
  3. Check that state counts add up. Feed 40 URLs and get 37 totaled states, and three URLs vanished. Fix that before you look at the data.
  4. Open five raw HTML files next to their extracted rows. This catches the silent parser error where the selector matched a wrapper and grabbed the wrong text.
  5. Review every blocked and malformed row, adjust the selector, the readiness wait or the policy decision, and re-run only those URLs.
  6. Schedule the re-crawl and keep the raw store immutable, so a parser change can be replayed instead of guessed.

A passing trial looks boring. The success rate is stable across two runs, every failure has a named reason, and every URL carries a compliance decision. Only then does scale buy you anything.

The next step takes ten minutes. Pick one target URL, run the three-question test from the first section, and write a single JSON line with its state and its decision before you write a line of scale-up code. Teams that skip that step end up rebuilding the same pipeline from scratch, which is why a structured approach to automated data collection starts with the log rather than the crawler.


Clearcote Labs maintains Clearcote, a de-Googled Chromium with fingerprint and identity controls built into the engine, and it ships as a drop-in for the Playwright and Puppeteer scripts you already run, with SDKs for Node, Python and .NET. When the escalation path needs a browser you don't want to maintain, our hosted browsers start in the cloud with one call and include residential IPs billed per GB. Point your first crawler at it and see what a browser with a reproducible identity does for your blocked and partial rows at Clearcote Labs.

#nodejs web scrape#Node.js scraping#Playwright scraping#Cheerio parser#web scraping tutorial

Clearcote puts this into practice

An open-source Chromium with fingerprint control compiled into the engine. A drop-in for Playwright & Puppeteer.

  • 297engine patches
  • 43,492lines added
  • 411Chromium files changed
  • 373checks per build

Engine numbers are for the Pro build; the free open build is a smaller, public patch set.

Free for one browser: GitHub, a card check or a company Google account. Never charged.