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

AI and automation

How do I download files with headless Puppeteer?

Tell the browser where to save downloads through a DevTools Protocol command, trigger the download, and wait for the file; or skip the browser download and fetch the file URL with the page's cookies.

Two ways to do it

Headless Chrome does not show a save dialog, and by default downloads may go nowhere useful. With Puppeteer you either enable downloads to a known folder using a Chrome DevTools Protocol command, then click the link and wait for the file to appear, or you read the file's URL from the page and download it yourself over HTTP with the browser's cookies. The second method is simpler and more robust when the URL is visible; the first is needed when the file is generated by script or behind a form submit.

Method one: let the browser download

import fs from "node:fs/promises";
import path from "node:path";
import pptrDl from "puppeteer";

const saveDir = path.resolve("downloads");
await fs.mkdir(saveDir, { recursive: true });
const chrome = await pptrDl.launch({ headless: true });
const sheetPage = await chrome.newPage();
const cdp = await sheetPage.createCDPSession();
await cdp.send("Browser.setDownloadBehavior", { behavior: "allow", downloadPath: saveDir, eventsEnabled: true });

const done = new Promise((resolve) =>
  cdp.on("Browser.downloadProgress", (e) => { if (e.state === "completed") resolve(e.guid); }));
await sheetPage.goto("https://portal.example.com/reports");
await sheetPage.click("a#export-csv");
await done;
console.log(await fs.readdir(saveDir));
await chrome.close();

The progress event tells you when the file is complete, which is more reliable than polling the folder for a name. CDP commands and their parameters change between Chrome versions now and then, so check the current protocol documentation if a command is rejected.

Method two: fetch the URL with the session

If the link has an href, read it and download it with Node's fetch, passing the browser's cookies so the server sees the same session:

const href = await sheetPage.$eval("a#export-csv", (a) => a.href);
const jar = await sheetPage.cookies(href);
const cookieHeader = jar.map((c) => `${c.name}=${c.value}`).join("; ");
const res = await fetch(href, { headers: { cookie: cookieHeader, "user-agent": await chrome.userAgent() } });
await fs.writeFile(path.join(saveDir, "report.csv"), Buffer.from(await res.arrayBuffer()));

Recent Puppeteer versions also offer cookie access on the browser context; use whichever your version documents.

Pitfalls

  • Files that open in a tab. PDFs may display in the built-in viewer instead of downloading. Fetch the URL directly, or add the download attribute behavior through the page.
  • Blob URLs. Files built in the page as blob: URLs cannot be fetched from Node. Read them inside the page with fetch(blobUrl) in page.evaluate and return base64.
  • Temporary names. Chrome writes .crdownload files while downloading. Wait for completion before reading.
  • Several downloads. Track them by the guid from the events, not by timing.

Downloads behind a CAPTCHA

Export and download buttons are a common place for a CAPTCHA, because they are expensive for the site. When a widget appears, read its site key, solve it, and inject the token before clicking. For a reCAPTCHA v2 checkbox, set the hidden g-recaptcha-response textarea and call the widget's callback if the page uses one. A reCAPTCHA v2 token arrives under 9 seconds. The Puppeteer integration guide shows the injection step in full, and finding the callback helps with pages that ignore the textarea.

Running in agents and pipelines

When an AI agent or RPA job triggers downloads, give each run its own download folder, clean it up afterwards, and return the file path to the next step instead of the file contents. Large files in an agent's context waste tokens. See also downloading files while scraping for the plain HTTP side, and the Puppeteer scraping guide for the broader setup.

Checking the file you got

A finished download is not always the file you wanted. Session timeouts and permission errors often produce a small HTML page saved under the expected name. After each download, check the size against a sensible minimum and read the first bytes: a CSV should start with its header row, a PDF with %PDF, a ZIP with PK. Reject and log anything else, so a broken export does not flow silently into the next step of your pipeline.

Common questions

Why do my headless downloads disappear?

Downloads are not enabled or go to a default folder; set the download behavior and path through CDP.

How do I know a download has finished?

Listen for Browser.downloadProgress events and wait for the completed state.

Can I download a PDF that opens in the viewer?

Yes. Fetch its URL directly with the page cookies instead of relying on the viewer.

What about files built as blob URLs?

Read them inside the page with fetch in page.evaluate and send the bytes back as base64.

Does a download button CAPTCHA need a browser?

Token widgets can be solved through the API; the browser only needs the token injected before the click.

Keep reading