NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

Web scraping with Axios and Cheerio

Axios fetches, Cheerio parses, and together they cover most static pages from Node.js without a browser. This guide builds a scraper you can leave running: a configured client, automatic retries, clean parsing and controlled concurrency.

Why this pair

Axios is a promise based HTTP client with features that suit scraping: instances with shared defaults, interceptors that run on every request and response, and automatic JSON parsing. Cheerio parses HTML on the server and gives you a jQuery like API to query it, without running scripts or rendering anything. That makes the pair fast and light: no browser process, no rendering cost. The limit is the same: if the data only exists after JavaScript runs, you need a browser or the JSON endpoint behind the page.

Setup

npm init -y
npm pkg set type=module
npm install axios cheerio

The examples use ES modules and need Node.js 18 or newer. Cheerio 1.x exposes load as a named export, which is all this scraper needs.

A configured Axios instance

Create one instance for the target site. Shared settings live there, so individual calls stay short, and the instance keeps its own interceptors without affecting other code that uses Axios.

// client.js
import axios, { isAxiosError } from 'axios';

export const site = axios.create({
  baseURL: 'https://directory.example.org',
  timeout: 20_000,
  maxRedirects: 5,
  headers: {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) listings-index/2.2',
    'Accept-Language': 'en-AU,en;q=0.9',
  },
  responseType: 'text',
});

responseType: 'text' keeps the body as a string for Cheerio even when a server mislabels HTML. The timeout covers the whole request; Axios has no default timeout, so always set one.

A retry interceptor

By default Axios rejects any response with a status of 400 or more. A response interceptor can catch those rejections, decide whether the error is worth retrying, wait, and send the same request again.

const RETRY_ON = new Set([429, 500, 502, 503, 504]);
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

site.interceptors.response.use(undefined, async (error) => {
  if (!isAxiosError(error) || !error.config) throw error;
  const cfg = error.config;
  const code = error.response?.status;
  const transient = code ? RETRY_ON.has(code) : error.code === 'ECONNRESET';
  cfg.retryCount = (cfg.retryCount ?? 0) + 1;
  if (!transient || cfg.retryCount > 3) throw error;
  const hinted = Number(error.response?.headers?.['retry-after']);
  const delay = Number.isFinite(hinted) && hinted > 0 ? hinted * 1000 : 800 * 2 ** cfg.retryCount;
  await sleep(delay + Math.random() * 400);
  return site.request(cfg);
});

The counter lives on the request config, so each request has its own budget of three retries. Retry-After is honored when the server sends it in seconds; otherwise the delay doubles each time, with a little random jitter. Errors that are not transient, such as 404, are thrown immediately.

Parsing with Cheerio

Load the HTML, select elements and read text or attributes. Cheerio's selectors follow CSS, so what works in DevTools' document.querySelectorAll usually works here.

// parse.js
import { load } from 'cheerio';

export function readListing(html, pageUrl) {
  const $ = load(html);
  const entries = $('ul.results > li').map((_, li) => {
    const row = $(li);
    return {
      name: row.find('h3').text().trim(),
      city: row.find('.location').first().text().trim() || null,
      url: new URL(row.find('a.details').attr('href') ?? '', pageUrl).href,
    };
  }).get();
  const nextHref = $('a[rel="next"]').attr('href');
  return { entries, next: nextHref ? new URL(nextHref, pageUrl).href : null };
}

.map(...).get() turns the Cheerio selection into a plain array. new URL(href, pageUrl) resolves relative links against the page they came from, which avoids broken links when a site mixes absolute and relative paths.

Following pages and limiting concurrency

Listing pages are usually fetched in order, because each one tells you where the next is. Detail pages can be fetched in parallel, but in small numbers. A tiny pool keeps a fixed number of requests in flight without any extra package.

// run.js
import { appendFile } from 'node:fs/promises';
import { setTimeout as pauseFor } from 'node:timers/promises';
import { site } from './client.js';
import { readListing } from './parse.js';

async function pool(items, size, task) {
  const queue = [...items];
  const runners = Array.from({ length: size }, async () => {
    while (queue.length) await task(queue.shift());
  });
  await Promise.all(runners);
}

let pageUrl = 'https://directory.example.org/listings?page=1';
for (let n = 0; pageUrl && n < 50; n += 1) {
  const { data } = await site.get(pageUrl);
  const { entries, next } = readListing(data, pageUrl);
  await pool(entries, 3, async (entry) => {
    const detail = await site.get(entry.url).catch(() => null);
    const phone = detail ? readPhone(detail.data) : null;
    await appendFile('listings.jsonl', JSON.stringify({ ...entry, phone }) + '\n');
  });
  pageUrl = next;
  await pauseFor(1500);
}

readPhone stands for whatever detail parser you need. Writing JSON Lines with appendFile stores each record as soon as it is ready, so an interrupted run keeps its progress. The page cap of 50 stops a broken pagination link from looping forever.

Test the parser against saved pages

Because readListing takes a string and returns plain objects, it is easy to test without touching the network. Save two or three real pages with curl -o fixtures/page1.html, then write a test with Node's built in runner (node --test) that loads each file and checks the number of entries and a few known values. When the site changes its markup, the scraper starts producing empty fields long before anyone notices in the data; a failing test points straight at the selector that broke. Keep the fixtures small and refresh them when you update selectors, so they always reflect what the site serves today. The same approach works for the detail parser and for the challenge detection described below.

When the HTML is empty

If Cheerio finds nothing but the browser shows data, the page probably fills itself with JavaScript. Before reaching for a browser, open DevTools, filter the Network panel by Fetch/XHR and reload. If a JSON response holds the data, call it with the same Axios instance and drop Cheerio for that page: site.get('/api/listings?page=1', { responseType: 'json' }). If not, render the page in a browser; see web scraping with Puppeteer.

Challenge pages and CAPTCHAs

Sometimes a response is a challenge instead of content, for example a form with a Turnstile widget. Cheerio is handy for spotting it: $('.cf-turnstile').attr('data-sitekey') returns the site key when one is present. Send that key and the page URL to a solving API, then post the form with Axios, including the token in cf-turnstile-response and any hidden inputs Cheerio can collect with $('form input[type=hidden]'). The guide on solving Turnstile in Node.js contains a ready client. Keep cookies between the page load and the post; Axios in Node does not store cookies by itself, so read set-cookie from the first response and send it back, or add a cookie jar library you trust.

Being a good citizen

  • Check robots.txt and the site's terms before you start.
  • Keep the pool small (two to four) and pause between listing pages.
  • Identify your client honestly or keep a realistic, consistent browser User-Agent.
  • Collect only what you need, and avoid personal data unless you have a lawful reason.
Axios plus Cheerio is ideal for directories, catalogs and documentation sites that serve complete HTML. It is quick to write, cheap to run and easy to debug with saved pages.

Common questions

Will Cheerio execute the page scripts?

No. It only parses the HTML string you give it. For JavaScript rendered content use a browser or the JSON endpoint the page calls.

Does Axios keep cookies between requests in Node.js?

Not by itself. Read set-cookie headers and send them back, or plug in a cookie jar library.

How do I retry 429 responses with Axios?

Add a response interceptor that checks the status, waits for Retry-After or an exponential delay, and calls the instance again with the same config.

How should I import Cheerio in an ES module?

Import the named load function from cheerio, or use a namespace import; both work with Cheerio 1.x.

How many requests should run in parallel?

Keep it small, often two to four per site, and add pauses between listing pages. Raise it only if the site responds comfortably.

Keep reading