JavaScript-rendered pages often return a minimal HTML shell and load the useful content later. This Playwright scraping tutorial shows how to inspect that workflow, wait for the right signals, extract structured records, handle pagination, and troubleshoot the failures that commonly produce empty or incomplete data.
Overview
A traditional HTTP scraper can only parse the response it receives. If a page fills product cards, search results, tables, or article text through client-side JavaScript, the initial response may not contain the data you can see in a browser. Playwright addresses this by controlling a real browser engine, allowing the page to execute its scripts before your scraper reads the rendered DOM.
That extra capability comes with extra responsibility. Browser automation is slower and more resource-intensive than a direct request, and a visible element does not always mean its data is ready. A reliable workflow separates navigation, readiness checks, extraction, validation, and storage.
Before crawling, confirm that you have permission to access and use the target data. Check the site's terms, applicable laws, access controls, and published crawling guidance. Do not attempt to bypass authentication, rate limits, CAPTCHAs, or other technical restrictions. For a practical pre-crawl review, see Web Scraping Legal and Ethical Checks.
Install and create a small test scraper
Use a current supported Node.js environment and install Playwright in a project rather than relying on an untracked global installation:
npm init -y
npm install playwright
npx playwright install
The browser installation command may download browser binaries separately from the package. Keep the Playwright package and browser binaries aligned in your development and deployment environments. When upgrading, read the release notes and rerun a small fixture or smoke test before a larger crawl.
A minimal extraction workflow
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({
userAgent: 'ExampleResearchBot/1.0 (contact: [email protected])'
});
try {
await page.goto('https://example.com/catalog', {
waitUntil: 'domcontentloaded',
timeout: 30000
});
await page.locator('[data-testid="product-card"]').first().waitFor({
state: 'visible',
timeout: 10000
});
const products = await page.locator('[data-testid="product-card"]').evaluateAll(cards =>
cards.map(card => ({
name: card.querySelector('[data-testid="name"]')?.textContent?.trim() ?? null,
price: card.querySelector('[data-testid="price"]')?.textContent?.trim() ?? null,
url: card.querySelector('a')?.href ?? null
}))
);
console.log(JSON.stringify(products, null, 2));
} finally {
await browser.close();
}
})();
This example uses explicit data attributes because they are often less fragile than deeply nested CSS selectors. Replace them after inspecting the target page. The optional chaining and null fallback prevent one missing field from crashing the entire extraction step, but you should still validate the resulting records before saving them.
Checklist by scenario
When content appears after page load
- Open the page with Playwright and inspect the DOM after the content appears.
- Identify a stable container or data attribute for one complete record.
- Wait for that record, a loading indicator to disappear, or a specific response to finish.
- Extract from the rendered DOM only after the readiness condition succeeds.
- Record the page URL and extraction timestamp with the data.
Avoid using a fixed delay as your primary synchronization method. waitForTimeout() can be useful while debugging, but a selector or response condition usually communicates the page's actual state more accurately.
When data arrives through an API
Use browser automation to understand the page, then consider whether an authorized, documented endpoint can provide the same data more efficiently. Playwright can observe responses while the page runs:
const responsePromise = page.waitForResponse(response =>
response.url().includes('/api/products') && response.request().method() === 'GET'
);
await page.goto('https://example.com/catalog', { waitUntil: 'domcontentloaded' });
const response = await responsePromise;
const payload = await response.json();
Only use an endpoint in a way that is permitted by the site and its access rules. If the response is stable and authorized, parsing JSON may be simpler than reading formatted text from the DOM. If not, keep the browser-based extraction and limit requests appropriately.
When the page has numbered or next-page pagination
const allRows = [];
for (let pageNumber = 1; pageNumber <= 10; pageNumber++) {
await page.goto(`https://example.com/catalog?page=${pageNumber}`, {
waitUntil: 'domcontentloaded'
});
const cards = page.locator('[data-testid="product-card"]');
await cards.first().waitFor({ state: 'visible', timeout: 10000 }).catch(() => {});
const rows = await cards.evaluateAll(elements => elements.map(element => ({
name: element.querySelector('[data-testid="name"]')?.textContent?.trim() ?? null,
url: element.querySelector('a')?.href ?? null
})));
if (rows.length === 0) break;
allRows.push(...rows);
}
console.log(allRows.length);
For a button-based interface, click the next control and wait for either a URL change, a response, or a change in the first record. Use a maximum page count and a duplicate check so a broken next button cannot create an endless loop.
When the page uses infinite scroll
Extract visible records after each scroll and stop when the record count no longer grows for a defined number of attempts. Keep a set of canonical URLs or stable IDs to remove duplicates. Do not scroll indefinitely without a business limit such as a maximum record count, time budget, or date boundary.
What to double-check
- Selectors: Prefer stable attributes, semantic roles, or recognizable text. Test selectors against several records, not just the first one. The guide to resilient CSS and XPath selectors provides a useful companion checklist.
- Wait conditions: Confirm that the condition represents usable data, not merely a page shell. A selector may exist while its text is still empty.
- Frames: Content inside an iframe must be accessed through the relevant frame rather than the main page locator.
- Requests and redirects: Log the final URL, response status, and content type during debugging. A consent page or redirect can look like a successful navigation.
- Multiple layouts: Mobile, desktop, logged-in, and logged-out views may use different markup. Test the context your production scraper will use.
- Data quality: Check required fields, duplicate IDs, unexpected currency or date formats, and suspiciously low record counts. Normalize the output only after capturing the raw value. See how to clean and normalize scraped data.
- Regression coverage: Save a small permitted HTML or browser fixture and test extraction against it. A fixture-based suite can reveal selector changes before a scheduled crawl fails; see how to test web scrapers.
Troubleshooting table
| Symptom | Likely cause | Useful check |
|---|---|---|
| Fields are empty | The selector matches a shell, hidden template, or wrong layout. | Inspect textContent, count matches, and save a screenshot or HTML snapshot. |
| Timeout waiting for a selector | The page redirected, failed to load, or uses a different readiness signal. | Log the final URL, status, title, and a short body excerpt. |
| Requests are blocked | The access pattern, volume, or environment triggered a site control. | Stop, review permission and site guidance, reduce unnecessary traffic, and do not try to bypass the control. |
| Only the first page is extracted | The next action is not awaited or the pagination state was not changed. | Verify the URL or first-record key changes after each action. |
| Browser fails in deployment | Browser binaries or system dependencies are missing or mismatched. | Run the documented browser install step in the deployment image and capture the browser version during diagnostics. |
Common mistakes
Scraping the initial response with a DOM parser: This misses content that exists only after JavaScript runs. First determine whether the data is present in the raw response, then choose the lightest permitted method.
Waiting for an arbitrary number of milliseconds: A fast run wastes time, while a slow run still fails. Prefer locator, URL, network, or content-based conditions and give each operation a bounded timeout.
Assuming visible text is the canonical value: Prices, dates, labels, and accessibility text can differ from the underlying value. Capture the appropriate attribute or structured response and document the choice.
Ignoring partial failures: A scraper that returns 2,000 records may still be wrong if a required field is missing on every record. Validate counts and required fields, and write failures to a separate log.
Launching a new browser for every URL: Reuse a browser and create isolated pages or contexts when appropriate. Close pages and the browser in cleanup code so scheduled jobs do not accumulate processes.
When to revisit
Revisit this workflow before a seasonal planning cycle, a major collection run, or any project that moves from a few test URLs to scheduled automation. Recheck selectors when the target site's layout, consent flow, pagination, login process, or frontend framework changes. A sudden drop in record count, a rise in null fields, new redirects, or repeated timeouts is a signal to pause collection and inspect the page rather than silently accepting bad output.
Also review the workflow whenever Playwright changes its APIs or supported browser behavior. Update the package and browser binaries together in a controlled branch, run smoke tests against representative pages, and compare output with a known fixture. Keep the extraction layer separate from cleaning and downstream delivery; this makes it easier to repair a selector without rewriting your pipeline. For structured output checks, use the practices in validating scraped data with JSON Schema.
Before the next run, use this short action list: confirm permission, test one URL manually, verify the readiness condition, extract a small sample, validate required fields, set request and page limits, log failures, and store enough metadata to reproduce the result. That checklist turns browser automation from a one-off script into a maintainable data workflow.