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

Web scraping

Web scraping with Puppeteer

Puppeteer controls Chrome from Node.js through the DevTools Protocol, which gives it a close view of everything the page does. Used well, that view makes scrapers faster and more reliable than clicking around a page.

What Puppeteer gives a scraper

Puppeteer launches Chrome or Chromium and talks to it over the Chrome DevTools Protocol. Besides the usual navigation and clicking, it can watch and change network traffic, run code inside the page, and read responses as they arrive. For scraping, three of those abilities matter most: waiting for the right moment, extracting data in bulk, and controlling which requests the page is allowed to make.

Install and launch

npm install puppeteer

The package downloads a compatible browser build during install. The examples below are ES modules for Node.js 18 or newer.

const puppeteer = (await import('puppeteer')).default;

const chromium = await puppeteer.launch({
  headless: true,
  args: ['--window-size=1366,900', '--lang=en-US'],
  defaultViewport: { width: 1366, height: 900 },
});
const page = await chromium.newPage();
page.setDefaultNavigationTimeout(45_000);

A fixed viewport keeps responsive layouts stable between runs. Setting a default navigation timeout once is cleaner than passing it to every goto.

Choosing the right navigation wait

page.goto accepts a waitUntil option that decides when navigation counts as done:

waitUntilResolves whenUse it for
domcontentloadedThe HTML is parsedFast default; pair with waitForSelector
loadThe load event firesPages whose data is in the initial HTML
networkidle2No more than 2 connections for 500 msPages that fetch data after load
networkidle0No connections for 500 msRarely; long polling pages never settle

The most reliable pattern is domcontentloaded followed by page.waitForSelector for the element that holds your data. It is precise and does not depend on how many analytics calls the page makes.

Extracting in bulk with $$eval

page.$$eval(selector, fn) runs a function inside the page with every matching element and returns the result to Node. One call replaces hundreds of element handles.

await page.goto('https://deals.example.org/today', { waitUntil: 'domcontentloaded' });
await page.waitForSelector('.deal-card');

const deals = await page.$$eval('.deal-card', (cards) =>
  cards.map((card) => ({
    title: card.querySelector('.deal-title')?.textContent.trim() ?? null,
    price: card.querySelector('[data-price]')?.getAttribute('data-price') ?? null,
    href: card.querySelector('a')?.href ?? null,
  })),
);
console.log(deals.length, deals[0]);

The function runs in the browser, not in Node, so it cannot use your Node variables. Pass values as extra arguments if you need them: page.$$eval(sel, (els, min) => ..., 10). Reading a.href inside the page returns an absolute URL, which saves resolving links later.

Blocking requests you do not need

Images, fonts and media rarely matter to a scraper, yet they make up much of a page's weight. Request interception lets you abort them before they load.

const SKIP_TYPES = new Set(['image', 'media', 'font']);
const SKIP_HOSTS = ['googletagmanager.com', 'doubleclick.net'];

await page.setRequestInterception(true);
page.on('request', (req) => {
  if (req.isInterceptResolutionHandled()) return;
  const host = new URL(req.url()).hostname;
  if (SKIP_TYPES.has(req.resourceType()) || SKIP_HOSTS.some((h) => host.endsWith(h))) {
    req.abort();
  } else {
    req.continue();
  }
});

Every intercepted request must be either continued or aborted, or the page hangs. The isInterceptResolutionHandled() check avoids errors when another handler already decided. Test the page with blocking on: a few sites hide content until a font or stylesheet loads.

Reading JSON instead of HTML

Many pages fetch their data as JSON and then render it. Puppeteer can catch those responses as they arrive, which gives you clean structured data without parsing the DOM.

const captured = [];
page.on('response', async (reply) => {
  const type = reply.request().resourceType();
  if ((type === 'xhr' || type === 'fetch') && reply.url().includes('/api/deals')) {
    try { captured.push(...(await reply.json()).items); } catch { /* not JSON */ }
  }
});
await page.goto('https://deals.example.org/today', { waitUntil: 'networkidle2' });
console.log('items from the API:', captured.length);

Once you know the endpoint, you may not need the browser at all: call it directly with fetch and the same headers. That is often the biggest speed gain available; see hidden API scraping.

Paging through results

When "Next" triggers a full navigation, start waiting before you click, so the navigation cannot finish before you begin to wait:

for (let round = 0; round < 20; round += 1) {
  const next = await page.$('a.pager-next');
  if (!next) break;
  await Promise.all([
    page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 30_000 }),
    next.click(),
  ]);
  await page.waitForSelector('.deal-card');
}

If the page loads results without navigating, wait for the data request instead with page.waitForResponse((r) => r.url().includes('/api/deals')) in the same Promise.all.

Sessions and cookies

Each browser keeps cookies for as long as it runs, so a consent choice, a login on your own test account or a solved challenge carries over to later pages automatically. To keep that state between runs, read the cookies after a successful session with await page.cookies(), store them as JSON, and restore them in the next run with await page.setCookie(...saved) before the first navigation. Newer Puppeteer releases also offer cookie methods on the browser object; check the API for your version. Restored cookies expire like any others, so detect a logged out or challenged page and refresh the session when needed. The note on saving cookies in Puppeteer goes through the details.

Several pages at once

One browser can run several tabs in parallel, which is lighter than launching several browsers. Open a small number of pages, give each one a share of the URL list, and let them work through their shares with Promise.all. Three or four tabs are plenty for most sites; beyond that you mostly add load and memory pressure without finishing much sooner. Apply request interception to each new page, because the setting is per page, and close every page when its share is done.

Cleanup

Wrap the work in try and call await chromium.close() in finally. A crashed script that leaves Chrome processes behind will eventually exhaust a server's memory. For long runs, reuse one browser and open a fresh page per batch, closing pages as you go.

Detection and CAPTCHAs

Headless Chrome is detectable through signals such as navigator.webdriver, and busy sites may answer with a challenge. Behave like a visitor: modest pacing, a normal viewport, and no unnecessary parallel tabs. When a token CAPTCHA appears, solve it through an API and place the token in the page with page.evaluate, then submit; the Puppeteer integration shows the full flow, and the note on debugging Puppeteer scripts helps when a page behaves differently in headless mode.

Blocking heavy resources is good for the site as well as for you: fewer bytes per page means less load on their servers. Combine it with low concurrency and public data only.

Common questions

Which waitUntil value should I use in page.goto?

domcontentloaded followed by waitForSelector for your data is the most reliable. networkidle2 suits pages that fetch data after load.

Why does my page hang after setRequestInterception?

Every intercepted request must be continued or aborted. A handler that skips some requests leaves them waiting forever.

Can I use Node variables inside $$eval?

Not directly, because the function runs in the browser. Pass them as extra arguments after the function.

How do I capture the JSON a page loads?

Listen to page.on response, filter by resource type and URL, and call res.json on matching responses.

Does blocking images change the page content?

Usually not, but some sites wait for fonts or styles before showing text. Test each site with blocking enabled.

Keep reading