WEB SCRAPING

Web Scraping with JavaScript and Node.js: Use the Cheapest Tool That Gets the Data

Web Scraping with JavaScript

What JavaScript web scraping is (and which problem you have)

Web scraping is code that downloads a page, pulls out the parts you care about, and stores them. Every scraper in this post is the same three-step loop: fetch the HTML, parse it into objects, store the objects.

The phrase "web scraping JavaScript" covers two different problems, though:

  1. Scraping with JavaScript. You write Node.js and want data from a site. That's this post.
  2. Scraping JavaScript-rendered sites. The page builds itself in the browser, so a plain download comes back empty. Rungs 2 and 3 below deal with that in any language. If you write Python, our Python web scraping guide covers the same ground.

Why Node and not a script in a browser tab? You can run document.querySelectorAll() in DevTools on the page you're looking at, and for a one-off grab that's fine. But a script in a tab can't read another site's HTML: the browser's CORS rules block cross-origin responses unless that server allows them. Node has no such rule. It's just a program making HTTP requests.

One check before you write any code: does the site have an official API or a data export? If it does, use that. Scraping is for when it doesn't.

Set up a Node.js web scraping project

You need Node 22 or newer. Today's scraping libraries have raised their floors, and a lot of tutorials still say "Node 18+":

PackageVersion (Nov 2026)Minimum Node
cheerio1.2.020.18.1
playwright1.64.120
puppeteer25.16.022.12.0
scrapebadger0.69.118

Versions and engine requirements from the npm registry, checked November 2026.

Create the project:

mkdir book-scraper && cd book-scraper
npm init -y
npm pkg set type=module
npm install cheerio

type=module turns on ES modules, so you get import syntax and top-level await without wrapping everything in an async function. Notice what's missing: axios. fetch is built into Node, so the HTTP client is one dependency you don't need anymore.

Prefer TypeScript? The same code works in a .ts file, and Cheerio ships its own type definitions.

Step 1: Fetch the HTML with native fetch

Our practice target is books.toscrape.com, a fake bookstore built for scraping practice: 1,000 books across 50 pages. Here's the fetch step:

const HEADERS = { 'User-Agent': 'Mozilla/5.0 (compatible; js-scraping-tutorial/1.0)' };

async function fetchHtml(url) {
  const res = await fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(15_000) });
  if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
  return res.text();
}

Three lines do the real work. The User-Agent says who you are instead of sending Node's default. AbortSignal.timeout() kills a request that hangs, so one slow page can't freeze the whole run. And the res.ok check is the line most people skip.

Here's why it matters. If you're coming from axios, you're used to errors throwing. fetch doesn't throw on a 404 or a 503. It hands you the error page, and res.text() returns its HTML like any other page:

const missing = await fetch('https://books.toscrape.com/catalogue/page-999.html');
console.log('page 999:', missing.status, missing.ok); // fetch did NOT throw

Without the check, your parser runs on an error page, finds zero books, and you spend twenty minutes debugging a selector that was never broken. Sound familiar?

One nice side effect: res.text() always decodes as UTF-8. This site sends no charset in its Content-Type header, which is why Python's requests library garbles the £ sign on it. In Node the price comes through clean.

Step 2: Parse it with Cheerio

Open the site, right-click a book, and pick Inspect. Each book is an <article class="product_pod">. Inside it: the title in a link inside an <h3>, the price in .price_color, stock in .availability, and the star rating as a class name like star-rating Three.

Cheerio gives you jQuery-style selectors over that HTML, in Node, with no browser:

import * as cheerio from 'cheerio';

const RATINGS = { One: 1, Two: 2, Three: 3, Four: 4, Five: 5 };

function parse(html, pageUrl) {
  const $ = cheerio.load(html);
  return $('article.product_pod')
    .map((_, el) => {
      const card = $(el);
      const link = card.find('h3 a');
      return {
        title: link.attr('title'),
        price: Number(card.find('.price_color').text().replace(/[^0-9.]/g, '')),
        inStock: card.find('.availability').text().includes('In stock'),
        rating: RATINGS[card.find('.star-rating').attr('class')?.split(' ')[1]] ?? null,
        url: new URL(link.attr('href'), pageUrl).href,
      };
    })
    .get();
}

A few choices worth explaining:

  • attr('title'), not .text(). The visible link text is cut short for long titles. The title attribute holds the full one.
  • The price regex strips everything except digits and the dot, so "£51.77" becomes the number 51.77, and a different currency symbol won't break it.
  • The rating lives in a class name, so we split the class string and map the word to a number.
  • new URL(href, pageUrl) turns relative links into absolute ones. Don't glue strings together; relative paths change from page to page.
  • .map().get() turns Cheerio's selection into a plain array.

Most important of all: parse() takes HTML and returns objects. It never touches the network. That's on purpose. Getting the HTML is the hard part of scraping; parsing it is the easy part. When a site starts fighting back later in this post, you'll replace fetchHtml() and this function won't change at all.

Test your parser without hitting the site

Because parse() is a pure function, you can test it against a saved copy of the page. Save it once while you're online, then run the test as often as you like with no network at all:

import assert from 'node:assert/strict';
import { mkdir, readFile, writeFile } from 'node:fs/promises';

const url = 'https://books.toscrape.com/catalogue/page-1.html';
await mkdir('fixtures', { recursive: true });
await writeFile('fixtures/page-1.html', await fetchHtml(url)); // once, while online

const books = parse(await readFile('fixtures/page-1.html', 'utf8'), url); // any time, offline
assert.equal(books.length, 20);
assert.ok(books.every((b) => b.title && b.price > 0 && b.rating));

Two payoffs. You stop sending the site a request every time you tweak a selector. And when the scraper breaks in production, you can tell in seconds which half broke. If the saved page still parses, the live site changed or started blocking you. If it doesn't, your selectors are wrong.

Step 3: Crawl every page without getting rate-limited

The simple way to get all 50 pages is to follow the "next" link until there isn't one:

import { setTimeout as sleep } from 'node:timers/promises';

const books = [];
let url = 'https://books.toscrape.com/catalogue/page-1.html';
while (url) {
  const html = await fetchHtml(url);
  books.push(...parse(html, url));
  const next = cheerio.load(html)('li.next a').attr('href');
  url = next ? new URL(next, url).href : null;
  await sleep(500); // be polite: half a second between pages
}

It works, and it's slow on purpose: one page at a time, half a second apart. For 50 pages that's fine. For 50,000 it isn't.

Node earns its place here. Its event loop can keep many requests in flight at once, so the obvious next move is to build every page URL and fire them together:

// Don't do this on a real site
const pages = await Promise.all(urls.map((u) => fetchHtml(u)));

That opens every request at the same moment. With 50 URLs you might get away with it. With 5,000, you're sending 5,000 simultaneous requests from one IP, and the site will answer with 429s or a ban. So Node's concurrency cuts both ways: it's why Node scrapers are fast and why they're often the first to get rate-limited.

The fix is a cap. This helper runs at most limit jobs at once and keeps results in order:

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

Each worker grabs the next index, does the job, and goes back for more. JavaScript runs your code on a single thread, so next++ can't be claimed twice. No locks, no dependency. If you'd rather use a package, p-limit does the same job.

The catalogue pages follow one pattern, from catalogue/page-1.html to catalogue/page-50.html, so build all 50 URLs and run them five at a time:

const rest = await mapLimit(urls, 5, async (url) => parse(await fetchHtml(url), url));

One more thing before you scale this up. If any single page throws, Promise.all rejects and you lose every result from the run, even the 49 pages that worked. On a long crawl that hurts. Catch errors per page and keep a list of what failed:

const failed = [];
const rest = await mapLimit(urls, 5, async (url) => {
  try {
    return parse(await fetchHtml(url), url);
  } catch (err) {
    failed.push({ url, error: err.message });
    return [];
  }
});
if (failed.length) console.warn(`${failed.length} pages failed:`, failed);

Now a 404 or a timeout costs one page, not the whole run. And you get a list to retry.

How high should the limit go? Start at 2 to 5 on a site you don't own. Raise it only if no 429s show up.

Bottom line: concurrency is Node's real advantage for scraping. Cap it from day one.

Step 4: Save to JSON and CSV

JSON is one line. CSV takes a little care, because text fields like titles can contain commas and quotes, and a naive join(',') would split them across columns:

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

function toCsv(rows) {
  const cols = Object.keys(rows[0]);
  const esc = (v) => {
    const s = String(v ?? '');
    return /[",\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
  };
  return [cols.join(','), ...rows.map((r) => cols.map((c) => esc(r[c])).join(','))].join('\n');
}

await writeFile('books.json', JSON.stringify(books, null, 2));
await writeFile('books.csv', toCsv(books));

Any value with a comma, quote or newline gets wrapped in quotes, and inner quotes are doubled. That's the standard CSV rule, and Excel and Google Sheets both read it.

The complete Node.js web scraper

Here's everything together. Save it as books.mjs and run node books.mjs:

import * as cheerio from 'cheerio';
import { writeFile } from 'node:fs/promises';

const BASE = 'https://books.toscrape.com/';
const TOTAL_PAGES = 50; // catalogue/page-1.html to catalogue/page-50.html
const HEADERS = { 'User-Agent': 'Mozilla/5.0 (compatible; js-scraping-tutorial/1.0)' };
const RATINGS = { One: 1, Two: 2, Three: 3, Four: 4, Five: 5 };

async function fetchHtml(url) {
  const res = await fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(15_000) });
  if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
  return res.text();
}

function parse(html, pageUrl) {
  const $ = cheerio.load(html);
  return $('article.product_pod')
    .map((_, el) => {
      const card = $(el);
      const link = card.find('h3 a');
      return {
        title: link.attr('title'),
        price: Number(card.find('.price_color').text().replace(/[^0-9.]/g, '')),
        inStock: card.find('.availability').text().includes('In stock'),
        rating: RATINGS[card.find('.star-rating').attr('class')?.split(' ')[1]] ?? null,
        url: new URL(link.attr('href'), pageUrl).href,
      };
    })
    .get();
}

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

function toCsv(rows) {
  const cols = Object.keys(rows[0]);
  const esc = (v) => {
    const s = String(v ?? '');
    return /[",\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
  };
  return [cols.join(','), ...rows.map((r) => cols.map((c) => esc(r[c])).join(','))].join('\n');
}

const started = Date.now();
const urls = Array.from({ length: TOTAL_PAGES }, (_, i) => new URL(`catalogue/page-${i + 1}.html`, BASE).href);

const failed = [];
const pages = await mapLimit(urls, 5, async (url) => {
  try {
    return parse(await fetchHtml(url), url);
  } catch (err) {
    failed.push({ url, error: err.message });
    return [];
  }
});
const books = pages.flat();
if (failed.length) console.warn(`${failed.length} pages failed:`, failed);

await writeFile('books.json', JSON.stringify(books, null, 2));
await writeFile('books.csv', toCsv(books));

const seconds = ((Date.now() - started) / 1000).toFixed(1);
console.log(`Scraped ${books.length} books from ${TOTAL_PAGES} pages in ${seconds}s`);
console.log(books[0]);

Run it and you'll have all 1,000 books in books.json and books.csv. That's a complete JavaScript web scraper in under 80 lines, with one dependency. For a static site at modest volume, you can stop here. Seriously. Everything below is for when a site won't cooperate.

Rung 2: The page is built with JavaScript, so read its data first

Now point the same idea at a page that renders itself. quotes.toscrape.com has two versions of the same quotes: a normal one and a JavaScript one at /js/. Here's a parser for a quote card:

function parseQuotes(html) {
  const $ = cheerio.load(html);
  return $('div.quote')
    .map((_, el) => ({
      text: $(el).find('.text').text(),
      author: $(el).find('.author').text(),
      tags: $(el).find('.tag').map((_, t) => $(t).text()).get(),
    }))
    .get();
}

Run it on both pages:

static page: 10 quotes
/js/ page, same parser: 0 quotes

Zero. The page looks identical in your browser, so what happened?

Open view source (Ctrl+U, or Cmd+Option+U on a Mac) instead of Inspect. Inspect shows the page after its JavaScript ran. View source shows what the server actually sent, which is what fetch gets. On /js/ there are no quote cards in it. There's a <script> with a var data = [...] array and a loop that writes each quote into the page.

Most tutorials launch a headless browser at this point. Don't, yet. The data is sitting right there in the HTML you already downloaded. Cheerio doesn't run scripts, but it can read them:

function extractEmbeddedData(html) {
  const $ = cheerio.load(html);
  const script = $('script')
    .map((_, s) => $(s).html())
    .get()
    .find((code) => code.includes('var data ='));
  if (!script) return null;
  const start = script.indexOf('[', script.indexOf('var data ='));
  const end = script.indexOf('];', start);
  return JSON.parse(script.slice(start, end + 1));
}
/js/ page, embedded data: 10 quotes
Albert Einstein | change, deep-thoughts, thinking, world

Ten quotes, structured, with no browser. Note what we didn't do: eval the page's script. Running code from a site you don't control inside your Node process is a bad idea. Slice out the array and JSON.parse it. That works here because the array is valid JSON; if a site writes a plain JavaScript object (unquoted keys, single quotes), parse fails and you'll know right away.

This pattern is everywhere on real sites. Next.js apps built on the Pages Router put the whole page's data in a <script id="__NEXT_DATA__" type="application/json"> tag, so it's one line: JSON.parse($('#__NEXT_DATA__').text()). Newer App Router sites split the data into self.__next_f.push() chunks instead, which is messier to read but still there. Product pages often carry structured data for search engines too, in a <script type="application/ld+json"> block with the name, price and availability:

const items = $('script[type="application/ld+json"]').map((_, s) => JSON.parse($(s).text())).get();
const product = items.find((i) => i['@type'] === 'Product');
console.log(product?.name, product?.offers?.price);

Real sites vary: some nest products inside an @graph array, some list several offers. Log the parsed object once and read its shape before you write the lookup.

Before you install a browser, search the page source for the value you want. If it's in there, you're done.

Rung 2b: Call the page's own API

Some pages don't ship the data at all. They download it after loading. The infinite-scroll version at quotes.toscrape.com/scroll works like that. Open DevTools, go to the Network tab, filter by Fetch/XHR, and scroll. You'll see requests to /api/quotes?page=1, ?page=2 and so on, each returning JSON.

So skip the page and call that endpoint yourself:

const all = [];
for (let page = 1; ; page++) {
  const res = await fetch(`https://quotes.toscrape.com/api/quotes?page=${page}`);
  const data = await res.json();
  all.push(...data.quotes);
  if (!data.has_next) break;
}
/api/quotes: 100 quotes, no HTML parsed

No HTML, no selectors, no browser. The site's own front end depends on that endpoint, so its shape tends to change less often than its CSS classes. Same manners apply: cap your concurrency and don't hammer it.

Bottom line: "it's a JavaScript site" doesn't mean "you need a browser." It means "look for the data before you render it."

Rung 3: When you need a real browser (Playwright or Puppeteer)

Sometimes the data really isn't anywhere you can fetch. The endpoint wants a token that the page's script computes, the content only shows up after a click, or the site checks that a real browser is on the other end. Now you render.

npm install playwright
npx playwright install chromium
import { chromium } from 'playwright';

const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://quotes.toscrape.com/js/', { waitUntil: 'domcontentloaded' });
  await page.waitForSelector('div.quote');
  const quotes = parseQuotes(await page.content());
  console.log(`rendered: ${quotes.length} quotes`);
} finally {
  await browser.close();
}
rendered: 10 quotes

See the last useful line: parseQuotes(await page.content()). The browser replaced the fetch step, and the parser from Rung 2 didn't change. Same split, new fetch.

There's a second way to pull data out, and it's one place where writing your scraper in JavaScript pays off directly. page.$$eval() runs a function inside the page itself, with the real DOM:

const authors = await page.$$eval('div.quote .author', (els) => els.map((el) => el.textContent));

The callback is plain browser JavaScript, the same code you'd test in the DevTools console first. Use it for quick grabs. For anything you want to test offline, stick with page.content() plus parse().

Playwright or Puppeteer? Both work. The practical differences:

Playwright 1.64.1Puppeteer 25.16.0
BrowsersChromium, Firefox, WebKitBuilt around Chrome ("control headless Chrome over the DevTools Protocol", per its npm description)
Browser downloadSeparate step: npx playwright installDownloads Chrome when you npm install
Minimum Node2022.12.0

Sources: playwright.dev and the npm registry, November 2026.

Playwright also auto-waits for elements to be actionable before clicking or typing, which removes a lot of manual sleep() calls when you have to interact with a page. If you're starting fresh, that's the one we'd pick.

The catch is cost. Every rendered page downloads and runs the site's scripts, styles, images and fonts, and each open page holds a chunk of memory. A few habits keep that under control:

const context = await browser.newContext();
await context.route('**/*', (route) =>
  ['image', 'font', 'media'].includes(route.request().resourceType()) ? route.abort() : route.continue(),
);
// then: const page = await context.newPage(); ... await page.close();
  • Launch one browser and open many pages in it. Launching a browser per URL is the classic slow-scraper mistake.
  • Block images, fonts and media you don't need, like the route above.
  • Cap concurrent pages with the same mapLimit() from Step 3. A browser tab is far heavier than a fetch.

Bottom line: a browser is the right tool when nothing lighter works. It's the wrong default.

Rung 4: The site blocks you

Eventually a site decides you're a bot. It doesn't always say so clearly. You'll see one of these:

  • 403 Forbidden: you're refused outright.
  • 429 Too Many Requests: slow down, often with a Retry-After header saying how long.
  • 503 Service Unavailable: sometimes a real outage, often a block.
  • 200 OK with a challenge page: the sneaky one. The status says success, but the body is a CAPTCHA or a "Just a moment..." screen.

That last case is why checking res.ok isn't enough. Check the body too:

const BLOCK_MARKERS = [
  /<title>\s*just a moment/i, // Cloudflare interstitial
  /cf-chl-|challenge-platform/i, // Cloudflare challenge scripts
  /captcha-delivery\.com|datadome/i, // DataDome
  /px-captcha|_pxhd/i, // PerimeterX / HUMAN
  /access denied|request unsuccessful/i, // Akamai, Imperva wording
];

function looksBlocked(status, html) {
  if ([403, 429, 503].includes(status)) return true;
  return BLOCK_MARKERS.some((re) => re.test(html.slice(0, 20_000)));
}

It's a heuristic, not a detector. Add markers as you meet new block pages.

The free fixes, roughly in order:

  1. Send real-looking headers. A browser-like User-Agent and an Accept-Language header get you past the laziest filters.
  2. Slow down. Lower the mapLimit() cap and add a delay. Plenty of 429s are self-inflicted.
  3. Retry with backoff, and respect Retry-After when the site sends it.
  4. Keep cookies across requests when a site sets a session on the first visit.

Here's the retry, built on looksBlocked():

async function fetchWithRetry(url, tries = 4) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(15_000) });
    const html = await res.text();
    if (!looksBlocked(res.status, html)) {
      if (!res.ok) throw new Error(`${res.status} for ${url}`);
      return html;
    }
    if (attempt === tries) throw new Error(`Still blocked (${res.status}) after ${tries} tries: ${url}`);
    const retryAfter = Number(res.headers.get('retry-after'));
    const waitMs = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000; // 2s, 4s, 8s
    await sleep(waitMs);
  }

One catch: Retry-After can be a number of seconds or an HTTP date. This version handles seconds and falls back to exponential backoff for anything else, which is the safe default.

Where does this stop working? When the site uses a real anti-bot service. Those look at more than headers: the reputation of your IP (datacenter IP ranges are easy to spot), your TLS and browser fingerprint, and how you behave. Stealth plugins for Puppeteer and Playwright patch some of the obvious headless giveaways, and the vendors keep updating what they check. That's an arms race, not a fix.

Bottom line: the free fixes handle rate limits and lazy filters. Proper anti-bot protection needs residential IPs, real browsers and someone keeping them current.

The same scraper with a web scraping API

At the top of the ladder, you hand the fetch step to a service that runs the proxies and browsers for you. Because parse() never touched the network, this is a swap of one function.

Web-Scraper-API runs on ScrapeBadger's infrastructure, so the SDK package is called scrapebadger. Install it and set your key (you get 1,000 free credits, no card):

npm install scrapebadger
export SCRAPEBADGER_API_KEY=your_key_here
import { ScrapeBadger, BlockedError, RateLimitError } from 'scrapebadger';

const client = new ScrapeBadger(); // reads SCRAPEBADGER_API_KEY from the environment

async function fetchHtml(url, { renderJs = false } = {}) {
  const result = await client.web.scrape(url, {
    format: 'html',
    renderJs,
    escalate: true, // if blocked, let the API retry with a stronger engine
    maxCost: 7, // never spend more than 7 credits on this page
  });
  console.log(`${url}: ${result.credits_used} credits, engine=${result.engine_used}, blocked=${result.blocking_detected}`);
  return result.content;
}

try {
  console.log(parseQuotes(await fetchHtml('https://quotes.toscrape.com/')).length, 'quotes (plain)');
  console.log(parseQuotes(await fetchHtml('https://quotes.toscrape.com/js/', { renderJs: true })).length, 'quotes (rendered)');
} catch (err) {
  if (err instanceof BlockedError) console.error('Blocked by', err.vendor, err.blockKind); // not charged
  else if (err instanceof RateLimitError) console.error('Slow down, retry after', err.retryAfter, 's');
  else throw err;
}

What each piece does:

  • renderJs runs the page in a real browser on our side. Leave it off for static pages; it costs more.
  • escalate lets the API retry with a stronger engine when a request gets blocked.
  • maxCost caps what one page can spend, so escalation can't surprise you on the bill.
  • credits_used, engine_used, blocking_detected come back on every result, so you can log exactly what each page cost and how it was fetched.
  • BlockedError means every attempt hit a wall. Blocked requests aren't charged.

Here's what a page costs, by how it's fetched:

Request typeCreditsPer 1,000 pages, pay as you goPer 1,000 pages, Starter plan
HTTP engine, simple proxy (default)3$0.45$0.25
Browser engine, simple proxy (default)7$1.05$0.57
HTTP engine, premium proxy13$1.95$1.07
Browser engine, premium proxy17$2.55$1.39

Cost per 1,000 pages = credits per request × price per 1,000 credits ($0.150 pay as you go, $0.082 on the $49 Starter plan). Credit costs from the pricing update that took effect 15 October 2026; plan prices from our pricing page. Pricing verified November 2026.

Concurrency still matters here. Every plan has a requests-per-minute limit, and subscriptions get higher limits than pay as you go. Keep the same mapLimit() cap from Step 3, set to stay under yours, and catch RateLimitError instead of hammering retries.

So the free credits cover about 333 plain pages or 142 rendered ones. That's enough to test it on the site that's blocking you before you pay anything. The rule from Rung 2 still applies, by the way: if the data is in the HTML, fetch it plain at 3 credits instead of rendering it at 7.

Don't want the SDK? It's one POST with the fetch you already know:

const res = await fetch('https://scrapebadger.com/v1/web/scrape', {
  method: 'POST',
  headers: { 'x-api-key': process.env.SCRAPEBADGER_API_KEY, 'content-type': 'application/json' },
  body: JSON.stringify({ url: 'https://quotes.toscrape.com/js/', render_js: true, format: 'html' }),
});
const data = await res.json();
console.log(res.status, data.credits_used, data.content?.length);

Setup details and more examples live on the Node.js integration page. For how rendering and anti-bot handling work on our side, see JavaScript rendering and anti-bot bypass. Full parameters are in the docs.

Common errors and quick fixes

These are the messages you're most likely to hit while following along, as Node 22 prints them:

What you seeWhat it meansFix
Warning: Module type of file:///.../scraper.js is not specifiedYou used import without "type": "module". Node reparses the file as an ES module and warnsRun npm pkg set type=module, or name the file .mjs
TimeoutError: The operation was aborted due to timeoutAbortSignal.timeout() fired: the server took too longRetry it later, or raise the timeout for slow sites
TypeError: fetch failedThe connection never happened. The real reason is in err.cause.code (for example ECONNREFUSED)Log err.cause. Under heavy concurrency, lower the limit
browserType.launch: Executable doesn't exist at ...Playwright is installed but its browser isn'tRun npx playwright install chromium
Your parser returns 0 itemsThe page is JavaScript-rendered, you got an error or block page, or the selector is wrongCheck res.ok, run looksBlocked(), then compare view source with Inspect

JavaScript vs Python for web scraping

Honestly, both are fine. Pick the one you already write.

Node wins on concurrency (many requests in flight, with no extra libraries) and on JavaScript-heavy targets, since you're working in the same language the page is written in. And the two main browser tools, Puppeteer and Playwright, are at home in Node.

Python wins on the gentle start and on what happens after scraping. requests plus BeautifulSoup is about the easiest first scraper there is, and pandas is hard to beat for cleaning the data afterwards. If that's your stack, read our Python web scraping guide. It builds the same fetch/parse split.

Scrape responsibly

A few rules keep you out of trouble. Read the site's robots.txt and terms before you start. Keep concurrency low and add delays, because your scraper's traffic is someone else's server bill. Don't collect personal data you don't need, and know the privacy rules that apply where you and your users are. And if a site offers an API, use it. None of this is legal advice: if the data matters to your business, check the rules that apply to you.

FAQ

Is JavaScript good for web scraping?

Yes. Node.js handles many requests at once without extra libraries, fetch is built in, and Cheerio parses HTML quickly with no browser. For pages that render themselves, Playwright and Puppeteer are JavaScript-first tools. The trade-off is that async code takes more getting used to than Python's line-by-line style.

Is JavaScript or Python better for web scraping?

Neither is better across the board. Node is stronger for high-concurrency crawling and JavaScript-heavy sites. Python is easier for beginners and has stronger data-analysis tools for afterwards. If you already know one, use it: the hard parts of scraping (finding the data, avoiding blocks) are the same in both.

Which Node.js library is best for web scraping?

Native fetch plus Cheerio covers static pages: fast, light, and no browser. Pages that need rendering or clicks call for Playwright. To crawl large sites with queues and retries built in, use a crawling library like Crawlee. Most scrapers only need the first combination, plus a concurrency cap.

Should I use Puppeteer or Playwright for scraping?

Either works. Playwright drives Chromium, Firefox and WebKit, and it waits for elements automatically before interacting with them. Puppeteer is built around Chrome and installs it with the package. If you're starting a new project, Playwright is the safer default. If you already have working Puppeteer code, there's little reason to switch.

How do I scrape a website that loads data with JavaScript?

First, look for the data before you render. Search the page source for a value you can see on screen: it's often in a script tag as JSON. Next, check the Network tab for a JSON endpoint the page calls, and call it directly. Only when both fail, render the page with Playwright, or a web scraping API with JavaScript rendering, and parse the result.

Stay on the lowest rung that works

Here's the rule we'd use: stay on the lowest rung that returns the data. Move up only when keeping the current rung alive costs you more than an afternoon a week. For a lot of sites, that's fetch and Cheerio forever.

When a site starts blocking you, swap fetchHtml() and keep everything else. You can try it on the site that's giving you trouble with 1,000 free credits, no card required.

Keep Reading

ScraperAPI vs Scrapingdog vs Web-Scraper-APIWeb-Scraper-API
Nov 5, 2026 · 11 min read

ScraperAPI vs Scrapingdog vs Web-Scraper-API: Which One Should You Pick & Why

Read post →
Scrapfly vs ZenRows vs Web-Scraper-API
Nov 5, 2026 · 9 min read

Scrapfly vs ZenRows vs Web-Scraper-API : Which Scraper API Should You Use?

Read post →
Nov 4, 2026 · 15 min read

Best Web Scraping MCP Servers (2026): 9 Compared on Real Cost

Read post →

Start Scraping in Minutes

1,000 free credits, no credit card required. Failed requests cost 0 credits.