Prompt

How do I build a headless browser workflow for data collection?

Technology / Testing & QA1 observationLast seen Oct 26, 2026

Latest observation

Oct 26, 2026OpenAI APIWeb search: off

A solid headless browser workflow for data collection usually has 5 parts:

  1. Define the target data and scope
  2. Automate page interaction
  3. Extract and normalize the data
  4. Handle reliability and anti-bot issues
  5. Store, monitor, and maintain the pipeline

1) Pick the right tool

Common choices:

  • Playwright: best default for modern sites, reliable, fast, great for Chromium/Firefox/WebKit
  • Puppeteer: good if you only need Chrome/Chromium
  • Selenium: useful for legacy setups or multi-language ecosystems

If you’re starting fresh, I’d usually recommend Playwright.

2) Basic architecture

A typical workflow looks like this:

  • Scheduler/orchestrator

    • Runs jobs on a schedule or event trigger
    • Examples: cron, Airflow, Prefect, Dagster
  • Browser worker

    • Launches headless browser
    • Navigates to pages
    • Waits for content to load
    • Clicks/scrolls/forms if needed
  • Extractor

    • Pulls DOM text, attributes, tables, JSON embedded in the page, or network responses
  • Cleaner/transformer

    • Converts raw scraped content into structured records
  • Storage

    • Database, object storage, CSV/JSON, data warehouse
  • Observability

    • Logs, screenshots, HTML snapshots, retries, alerts

3) Example workflow with Playwright

Here’s a simple Node.js example:

import { chromium } from 'playwright';

async function run() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  await page.goto('https://example.com', { waitUntil: 'networkidle' });

  const title = await page.locator('h1').textContent();

  console.log({ title });

  await browser.close();
}

run().catch(console.error);

4) Extraction patterns

You can collect data from several sources:

A. DOM scraping

Use selectors to extract visible text and attributes.

const items = await page.locator('.product').evaluateAll(nodes =>
  nodes.map(n => ({
    name: n.querySelector('.name')?.textContent?.trim(),
    price: n.querySelector('.price')?.textContent?.trim(),
  }))
);

B. Embedded JSON

Many sites include JSON in scripts or __NEXT_DATA__-style blobs.

const data = await page.locator('script#__NEXT_DATA__').textContent();

C. Network traffic

Sometimes the browser requests a JSON API behind the UI. This is often cleaner than scraping rendered HTML.

page.on('response', async (response) => {
  const url = response.url();
  if (url.includes('/api/')) {
    const json = await response.json().catch(() => null);
    console.log(url, json);
  }
});

5) Reliability tips

Headless workflows break often unless you build in resilience.

  • Wait for specific elements, not arbitrary timeouts
  • Retry transient failures
  • Save screenshots and HTML on errors
  • Use stable selectors
  • Detect and handle pagination/infinite scroll
  • Limit concurrency
  • Respect rate limits
  • Rotate sessions only if appropriate and allowed
  • Set a realistic user agent and viewport

Example of robust waiting:

await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.locator('.results').waitFor({ state: 'visible' });

6) If data is behind forms or navigation

Automate user flows:

await page.fill('#search', 'laptops');
await page.click('#submit');
await page.waitForLoadState('networkidle');

For infinite scrolling:

let previousHeight = 0;
while (true) {
  const height = await page.evaluate(() => document.body.scrollHeight);
  if (height === previousHeight) break;
  previousHeight = height;
  await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
  await page.waitForTimeout(1000);
}

7) Production concerns

If you want this to run reliably in production:

  • Run browsers in containers
  • Use a job queue for scale
  • Capture metrics: success rate, latency, failure reasons
  • Keep parsing logic versioned
  • Store raw snapshots for debugging
  • Add alerting when a selector fails

8) Ethical and legal considerations

Make sure you:

  • Follow the site’s Terms of Service
  • Respect robots.txt where applicable
  • Don’t overload servers
  • Avoid collecting personal data unless you have a lawful basis
  • Use APIs when they exist

9) Recommended stack

A practical stack might be:

  • Playwright
  • Node.js or Python
  • PostgreSQL for structured data
  • S3/GCS for raw HTML/screenshots
  • Cron/Airflow/Prefect for scheduling
  • Docker for deployment

10) Suggested build sequence

Start simple:

  1. Build a script that fetches one page
  2. Add extraction for the fields you need
  3. Add retries and logging
  4. Add pagination and multiple URLs
  5. Add storage
  6. Add monitoring and error capture
  7. Containerize and schedule it

If you want, I can also give you:

  • a Python Playwright template
  • a Node.js production-ready scraper skeleton
  • or a Dockerized headless browser workflow example

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.