Prompt
How do I build a headless browser workflow for data collection?
Latest observation
A solid headless browser workflow for data collection usually has 5 parts:
- Define the target data and scope
- Automate page interaction
- Extract and normalize the data
- Handle reliability and anti-bot issues
- 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:
- Build a script that fetches one page
- Add extraction for the fields you need
- Add retries and logging
- Add pagination and multiple URLs
- Add storage
- Add monitoring and error capture
- 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