Web Scraping in JavaScript with Node.js
Web scraping in JavaScript takes two pieces in Node.js: the built-in fetch to download a page and cheerio to query its HTML with CSS selectors, the way you would with jQuery. That covers static pages. When a page builds its content in the browser, fetch returns an empty shell, and you need a headless browser such as Playwright, or a scrape endpoint that renders the page for you. This tutorial builds all three for quotes.toscrape.com, a site made for practice, with complete Node 22 code.
What do you need for web scraping in JavaScript?
You need Node.js 18 or later for the built-in fetch, plus cheerio to parse HTML. We used Node 22, cheerio 1.2.0 and robots-parser 3.0.1, and Playwright 1.63 for the rendering step. Install the packages in a new folder:
npm init -y
npm install cheerio robots-parser
The target is quotes.toscrape.com, a sandbox built for scraping practice and the site Scrapy's own tutorial uses. Each quote sits in a div.quote with the text in span.text, the author in small.author and tags in div.tags a.tag; the next page link is in li.next a (Scrapy tutorial, 2026). It also has a /js/ version whose quotes are generated by JavaScript, which makes it a good test of the second half of this tutorial.
Name your files .mjs (or set "type": "module" in package.json) so import and top-level await work.
How do you scrape a static page with fetch and cheerio, step by step?
The script below follows the site's pages, checks each URL against robots.txt, parses every quote into an object, waits two seconds between pages and writes the result to JSON. It's the whole program; the steps after it explain each part. Save it as scrape.mjs:
import { writeFile } from "node:fs/promises";
import * as cheerio from "cheerio";
import robotsParser from "robots-parser";
const BASE = "https://quotes.toscrape.com/";
const USER_AGENT = "quotes-tutorial/1.0 (you@example.com)";
const DELAY_MS = 2000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function loadRobots() {
const robotsUrl = new URL("/robots.txt", BASE).href;
const res = await fetch(robotsUrl, { headers: { "User-Agent": USER_AGENT } });
return robotsParser(robotsUrl, res.ok ? await res.text() : "");
}
async function fetchHtml(url) {
const res = await fetch(url, {
headers: { "User-Agent": USER_AGENT },
signal: AbortSignal.timeout(30_000),
});
if (res.status === 404) return null;
if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
return res.text();
}
export function parseQuotes(html, pageUrl) {
const $ = cheerio.load(html);
const quotes = $("div.quote")
.map((_, el) => {
const text = $(el).find("span.text").text().trim();
const author = $(el).find("small.author").text().trim();
if (!text || !author) return null; // skip a block whose layout changed
const tags = $(el).find("div.tags a.tag").map((_, t) => $(t).text().trim()).get();
return { text, author, tags };
})
.get();
const next = $("li.next a").attr("href");
return { quotes, next: next ? new URL(next, pageUrl).href : null };
}
export async function scrape(maxPages = 3) {
const robots = await loadRobots();
const all = [];
let url = BASE;
for (let page = 1; url && page <= maxPages; page++) {
if (!robots.isAllowed(url, USER_AGENT)) {
console.log(`robots.txt disallows ${url}; stopping`);
break;
}
const html = await fetchHtml(url);
if (html === null) break;
const { quotes, next } = parseQuotes(html, url);
if (quotes.length === 0) {
console.log(`page ${page}: no quotes found; the layout changed or the page needs JavaScript`);
break;
}
all.push(...quotes);
console.log(`page ${page}: ${quotes.length} quotes`);
url = next;
await sleep(DELAY_MS);
}
return all;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const quotes = await scrape();
await writeFile("quotes.json", JSON.stringify(quotes, null, 2));
console.log(`saved ${quotes.length} quotes to quotes.json`);
}
Run it with node scrape.mjs. The site wasn't reachable from the environment we wrote this in, so we tested parseQuotes() on HTML with the site's markup and the page loop with a mocked fetch. A quote block parsed to { text: '“Quote 1a.”', author: 'Author A', tags: [ 'change', 'world' ] }, a block with no text was skipped, and the loop followed li.next across two pages and stopped when the link was gone. Check a few rows against the live site before you rely on it.
Step 1: check robots.txt once
loadRobots() downloads robots.txt once and robots.isAllowed() checks each URL against it for your user agent. The rules are the site's published instructions for automated clients (RFC 9309, 2022); they aren't permission on their own, so read the site's terms as well.
Step 2: fetch with a timeout and a real User-Agent
AbortSignal.timeout(30_000) stops a hung request after 30 seconds, which fetch doesn't do by default. A 404 ends the crawl; any other error status throws, because a 403 or 429 means you should stop and look rather than push on.
Step 3: parse with cheerio
cheerio.load() parses the HTML; $("div.quote") selects every block; .map(...).get() turns them into a plain array, and returning null from the callback drops a block. new URL(next, pageUrl) resolves the relative next-page link.
Step 4: pace and stop
The loop sleeps 2 seconds per page and stops at maxPages, at a missing next link or at a page with no quotes. That last check matters: an empty page is how you find out the layout changed.
What do you do when the page needs JavaScript?
First confirm it: if the HTML from fetch doesn't contain the text you see in the browser, the page renders its content with JavaScript after loading. On quotes.toscrape.com, /js/ is that case; the site describes its content as generated by JavaScript (toscrape.com, 2026). You then have three options, from cheapest to heaviest.
- Find the data request. Open the browser's network tab, reload, and look for a JSON response with the data. Calling that URL with
fetchis faster and steadier than rendering, if the site's terms allow it. - Render with a headless browser. Playwright runs Chromium, executes the page's scripts and hands you the final HTML, which you parse with the same
parseQuotes(). - Use a scrape endpoint with rendering. One HTTP call returns the rendered page; covered in the next section.
The Playwright version, as render.mjs (install with npm install playwright and npx playwright install chromium):
import { chromium } from "playwright";
import { parseQuotes } from "./scrape.mjs";
const url = process.argv[2] ?? "https://quotes.toscrape.com/js/";
const browser = await chromium.launch();
try {
const page = await browser.newPage({ userAgent: "quotes-tutorial/1.0 (you@example.com)" });
await page.goto(url, { timeout: 30_000 });
await page.waitForSelector("div.quote", { timeout: 10_000 });
const { quotes } = parseQuotes(await page.content(), url);
console.log(`${quotes.length} quotes after rendering`, quotes[0]);
} finally {
await browser.close();
}
We ran it against a local page that inserts a quote with a script 300 ms after load. parseQuotes() found 0 quotes in that page's raw HTML and 1 after Playwright rendered it: { text: '“Rendered.”', author: 'Author C', tags: [ 'js' ] }. A browser per page costs far more memory and time than fetch, so render only the pages that need it.
If a site answers with a CAPTCHA, a challenge page or a block, stop. That's the site saying no to automated access; don't try to get around it with stealth plugins or rotating proxies. Look for an official API or a licensed data source instead.
How do you get the same page with one API call?
The scrape endpoint fetches the page for you, optionally renders its JavaScript, and returns it as json or markdown. GET /v1/web-scraper/scrape takes a required url (up to 2048 characters) and optional javascript, include_html and response_type. Each successful call costs 1 credit:
const endpoint = new URL("https://api.perceptlayer.com/v1/web-scraper/scrape");
endpoint.searchParams.set("url", "https://quotes.toscrape.com/js/");
endpoint.searchParams.set("javascript", "true");
endpoint.searchParams.set("response_type", "markdown");
const res = await fetch(endpoint, {
headers: { "X-API-Key": process.env.API_KEY },
signal: AbortSignal.timeout(90_000),
});
if (!res.ok) {
const { error } = await res.json();
throw new Error(`${res.status} ${error.code}: ${error.message}`);
}
console.log("credits used:", res.headers.get("X-Credits-Used"));
console.log(await res.text());
We didn't run this against the live API, and we haven't recorded a response from this endpoint, so we can't show what it returns. Run it in the playground on the Web Scraper API page to see the output before you parse it. Errors come back as an HTTP status with {"error": {"code", "message", "request_id"}}, and a failed call returns X-Credits-Used: 0; the errors docs list the codes.
What does each route cost?
Your own fetch and cheerio scraper costs no credits, only hosting and the time to keep it working. A Playwright scraper costs more hosting, because each page runs a browser. The scrape endpoint costs 1 credit per successful page, rendered or not.
| Job | Calls a month | Credits |
|---|---|---|
| 500 pages weekly | 500 × 4 | 2,000 |
| 300 JavaScript pages daily | 300 × 30 | 9,000, within the Starter pack's 10,000 |
| 2,000 pages daily | 2,000 × 30 | 60,000, within the Growth pack's 200,000 |
Every account gets 100 free credits after verifying an email address; see pricing for what credits cost. Calls run at 1 request a second on a free account and at least 5 a second on a paying one; a 429 tells you to wait, and HTTP 429 Too Many Requests shows how to handle it.
Pick by the page: fetch and cheerio for static HTML you're allowed to collect, Playwright when you need to drive a page yourself, and the endpoint when you'd rather not run browsers. For the Python version of this tutorial, see Web Scraping with Python; for turning pages into model input, see Website to Markdown. To try the endpoint, get a free API key.
APIs in this post
Frequently asked questions
Is JavaScript or Python better for web scraping?
Neither is better at the core job: both fetch HTML and query it with selectors. Node is a natural fit if your stack is JavaScript or you drive browsers with Playwright or Puppeteer; Python has Scrapy, a full crawling framework with scheduling and pipelines built in. Pick the language your team maintains, since maintenance is most of a scraper's cost.
What is cheerio?
Cheerio is a Node.js library that parses HTML and lets you query and change it with a jQuery-like API, such as $("div.quote").find("span.text").text(). It doesn't run JavaScript or load images and styles, which is why it's fast and why it can't see content a page renders in the browser.
Do I need Puppeteer or Playwright for web scraping?
Only for pages that render their content with JavaScript, or that need clicks and scrolling to reveal it. For static HTML, fetch and cheerio are faster and lighter. Check first by searching the fetched HTML for text you can see in the browser; if it's there, you don't need a browser.
How do I avoid getting blocked when scraping?
Scrape only what the site allows: follow robots.txt and the terms, identify yourself in the User-Agent, keep to one request at a time with a delay, and back off on 429 or 503. If you're blocked anyway, the site doesn't want automated access; stop rather than work around it, and look for an API.
How much does the scrape endpoint cost per page?
One credit per successful call, whether or not you set javascript=true, and nothing for a failed call. Every account gets 100 free credits after verifying an email address, and purchased credits last 12 months. The credits docs explain balances and the X-Credits-Remaining header.