Scrape a JavaScript website with Playwright, and when not to
TL;DR
- To scrape a JavaScript website, you often don’t need a browser. The data usually sits in the HTML or arrives as JSON.
- Check that first. A plain request is much faster and cheaper than Playwright.
- Use Playwright only when the page truly needs a browser. Then wait for elements, not timers, and catch the JSON it loads.
Your scraper sees an empty page. Here’s why
You open a site and see 50 products. Your script fetches the same address and finds 0.
The site sends a near-empty page first. Then its JavaScript fetches the data and draws the list. A plain HTTP library like Requests never runs that JavaScript, so it only gets the shell.
You can see this on a practice site. The JavaScript version of Quotes to Scrape shows 10 quotes in your browser. Fetch it with code and look for class="quote": it isn’t there.
That doesn’t mean you need Playwright yet. Look at where the data comes from first.
Here is what happens on that practice page. The HTML holds the 10 quotes as a list called var data. A small script below it loops over the list and writes one <div class='quote'> per quote into the page.
This is called client-side rendering: the server sends the raw data, and your browser builds the page. Requests sees what the server sent. Your browser shows what the script built. Same address, two different pages.
One warning: 0 items can also mean a block page. The site may have sent “Access denied” instead of the shell. Save the HTML your script got to a file and open it. You will see which one it is in a second.
Check three places before you start a browser
Open the page in Chrome, then:
- Search the source. Press
Ctrl+U(Mac:Cmd+Option+U) and search for a word you see on the page. Found it as plain text? Requests works. - Search the scripts. Found it inside a
<script>tag, as JSON? Cut it out with a few lines of code. No browser. - Watch the Network tab. Developer tools → Network → Fetch/XHR, then reload or scroll. A request that returns your data as JSON is a hidden API. Call it directly.
Only if all three come up empty do you need a real browser.
| what you found | use | cost |
|---|---|---|
| data in the HTML | Requests + a parser | lowest |
JSON inside a <script> tag |
Requests + a regex | lowest |
| a JSON request in the Network tab | call that URL with Requests | low |
| nothing, or the site checks for a real browser | Playwright | highest |
Why the gap is big: the 2025 Web Almanac puts the HTML of a median mobile home page at 22 KB. The same page also loads 632 KB of JavaScript and 911 KB of images. A browser downloads and runs all of that. Requests takes only the HTML.
Why Ctrl+U and not the Elements panel: the page source is what the server sent, which is exactly what Requests gets. The Elements panel shows the page after the scripts ran, so it always has the data.
We measured the cheap paths on the practice site (run 25 Nov 2026, 23:58 UTC, 5 plain Node fetches each, median):
| what we fetched | size | time |
|---|---|---|
/js/ page, HTML only |
5.8 KB | 143 ms |
/api/quotes?page=1, JSON |
2.9 KB | 144 ms |
A browser can’t stop at the HTML. The /js/ page also pulls in bootstrap.min.css (126 KB), jquery.js (84 KB) and main.css (1.4 KB). That is 217 KB before the page’s own script runs, about 37 times the HTML. Sizes are after unzipping.
We didn’t time a browser. Its start-up time depends on your computer, so one number from ours would mislead you. For scale, Browserbase’s pricing page says a typical scrape runs in under 2 minutes.
The data is often already in the HTML
The Quotes /js/ page is a good example. Its quotes aren’t missing. They sit in the page as var data = [...], and a script writes them out after load.
So skip the browser and read the JSON:
import json, re, requests
html = requests.get("https://quotes.toscrape.com/js/", timeout=30).text
match = re.search(r"var data = (\[.*?\]);", html, re.S)
quotes = json.loads(match.group(1))
print(len(quotes), quotes[0]["author"]["name"]) # 10 Albert Einstein
Real sites do the same thing under other names. Search the source for application/json or application/ld+json script tags, or for a word from the page.
How the code works:
re.searchfinds the text betweenvar data =and the first];. That works here because the tag lists inside end with],, not];.re.Slets the.match line breaks, since the list spans many lines.json.loadsturns the text into Python lists and dicts. It only works because this list is valid JSON: every key has double quotes.
On real sites, a <script type="application/json"> tag is the easy case: it holds data meant for code. A JavaScript blob is harder. If json.loads fails, the text is JavaScript, not JSON (single quotes, trailing commas). Paste the error and the first lines of the blob into your AI and ask for a parser that fits.
A hidden JSON API beats the browser
The scroll version loads more quotes as you scroll. In the Network tab you’ll see why: each scroll calls /api/quotes?page=N.
That API returns clean JSON with a has_next flag. On page 10, has_next turns false. Loop over it:
import requests
rows, page = [], 1
while True:
r = requests.get("https://quotes.toscrape.com/api/quotes",
params={"page": page}, timeout=30)
r.raise_for_status()
data = r.json()
rows += data["quotes"]
if not data["has_next"]:
break
page += 1
print(len(rows), "quotes")
No scrolling, no waiting, no browser. Same data.
The page’s own script shows the deal. It calls $.get('/api/quotes', {page: page}) and checks data.has_next before loading more. Your loop does the same thing, minus the scrolling.
The JSON carries more than the quotes: page, tag and a top_ten_tags list come along. Hidden APIs often give you fields the page never shows.
It’s also smaller. In our run, the JSON for 10 quotes was 2.9 KB against 5.8 KB for the HTML page with the same 10 quotes.
On a real site: in the Network tab, right-click the request, choose “Copy as cURL”, and paste it into your AI. If the call fails outside the browser, it likely needs the browser’s cookies or a token. That’s when the Playwright tricks below help.
When you do need Playwright
Playwright drives a real Chromium, Firefox or WebKit from code. Reach for it when:
- the data comes from requests you can’t copy (signed URLs, tokens made in the page)
- you must click, type or log in to reach the data
- the site runs a JavaScript check that a plain request can’t pass
Install it, plus one browser:
npm install playwright && npx playwright install chromium
# Python: pip install playwright && playwright install chromium
This scrapes the /js/ page with a real browser. Save it as scrape.mjs and run node scrape.mjs. The same code is valid TypeScript.
import { chromium } from 'playwright';
const browser = await chromium.launch(); // no window by default
const page = await browser.newPage();
// Skip images, fonts and video: less data, faster pages
await page.route('**/*', route =>
['image', 'font', 'media'].includes(route.request().resourceType())
? route.abort()
: route.continue());
await page.goto('https://quotes.toscrape.com/js/');
const quotes = page.locator('.quote');
await quotes.first().waitFor(); // wait for the data, not a timer
const rows = await quotes.evaluateAll(els => els.map(el => ({
text: el.querySelector('.text')?.textContent ?? '',
author: el.querySelector('.author')?.textContent ?? '',
})));
console.log(rows.length, rows[0]);
await browser.close();
The same in Python:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://quotes.toscrape.com/js/")
quotes = page.locator(".quote")
quotes.first.wait_for()
texts = quotes.locator(".text").all_inner_texts()
print(len(texts), texts[0])
browser.close()
Playwright is Microsoft’s free, open-source browser framework (Apache-2.0). It works from JavaScript, TypeScript, Python, .NET and Java, with one API for all three browser engines.
What the TypeScript code does, line by line:
chromium.launch()starts a browser with no window. That is the headless mode.page.route('**/*', …)sees every request the page makes.resourceType()says what it is, androute.abort()drops it.quotes.first().waitFor()pauses until the first quote is on the page.evaluateAllruns your function inside the page, on every match, and sends back plain data.
npx playwright install chromium downloads one browser. A bare playwright install fetches Chromium, Firefox and WebKit. Prefer Puppeteer or Selenium? Compare them on browser automation.
Selenium vs Node.js
You don’t pick one of the two. They do different jobs.
- Selenium drives a real browser. It is a library your code calls.
- Node.js runs JavaScript outside the browser. It is where your code runs.
- So Selenium can run inside Node.js:
npm install selenium-webdriveris its official JavaScript package. - Playwright, the code above, runs in Node.js too.
The real choice is Selenium vs Playwright vs Puppeteer: Selenium · all browser automation tools.
Wait for the element, never for a timer
Playwright’s own docs mark three ways of waiting as discouraged:
page.waitForTimeout(3000): the docs say it is for debugging only and makes runs flaky.waitUntil: 'networkidle': waits until nothing loads for 500 ms. The docs say to check for the content instead.page.waitForSelector(): replaced by locators. Uselocator.waitFor(), as above.
Locators also wait on their own before every click or fill. So most scripts need one wait: for the first row of data.
A timer guesses. Wait 3 seconds and a slow page isn’t ready yet. Wait 10 and a fast page wastes 9. The Playwright docs say a timer in production makes runs flaky, and point to real signals instead: network events, or an element becoming visible.
networkidle is a guess too. It only means nothing loaded for 500 ms, not that your data arrived.
Waiting on an element is a real signal. If the element never shows, the wait throws an error after its timeout. That’s what you want: you learn the page changed, instead of saving empty rows.
Need to wait for text, not just an element? locator.waitForFunction(), added in v1.62, waits until your check on the element returns true.
Let Playwright catch the JSON for you
Even inside a browser, the HTML is often the hard way. Grab the JSON the page loads instead. Start waiting before the action that triggers it:
const apiCall = page.waitForResponse(r => r.url().includes('/api/quotes'));
await page.goto('https://quotes.toscrape.com/scroll');
const data = await (await apiCall).json();
console.log(data.quotes.length, data.has_next); // 10 true
with page.expect_response(lambda r: "/api/quotes" in r.url) as info:
page.goto("https://quotes.toscrape.com/scroll")
data = info.value.json()
You get the same fields the page uses, with no HTML to parse and no CSS selectors to break.
A good middle path: let the browser load the page once to get the cookies, then call the API with page.request.get(url). Playwright sends the browser’s cookies with it and saves new ones back.
Why start waiting first: the docs’ own examples create the wait, then click, then await it. If you click first, the response can arrive before you start listening, and the wait runs into its timeout.
waitForResponse takes three kinds of match: a glob like '**/api/fetch_data', a RegExp, or a function that gets each response and returns true or false. Python’s expect_response takes the same, inside a with block.
The cookie path in more detail. Requests made with page.request or context.request read the browser’s cookies, and a Set-Cookie in the answer updates them. So the browser passes the site’s checks once, and your API calls ride on that session. Pages after the first need no page load at all.
Blocked inside Playwright? Read the error first
A real browser passes JavaScript checks that Requests can’t. It also has tells of its own. In Chrome, navigator.webdriver turns true when the browser starts with --headless or --enable-automation, and any page script can read it.
Find what caught you:
| you see | read |
|---|---|
403 |
403 Forbidden |
| “Error 1020” on a Cloudflare page | Cloudflare 1020 |
| “Just a moment…” that never clears | Cloudflare Just a moment |
| “Access Denied” with “Reference #18” | Akamai Access Denied |
| “You have been blocked” or a slider CAPTCHA | DataDome |
| a rotate-the-object puzzle, or “We’ve used Arkose Labs’ MatchKey” | Arkose Labs MatchKey |
Then the options, cheapest first:
- Slow down and keep one browser context (one set of cookies) per session.
- Add a proxy. Playwright takes one per browser or per context.
- Try a patched browser: Patchright (Playwright that hides common automation signs) or Camoufox (Firefox that changes its fingerprint).
- Rent a browser in the cloud.
The full checklist is in how to avoid getting blocked.
navigator.webdriver is a flag every page script can read. MDN lists what turns it on in Chrome: the --enable-automation or --headless flag, or --remote-debugging-port set to port 0.
The options in more detail:
- A browser context is one private cookie jar. Keep one per session, so you look like one visitor coming back, not many new ones.
- Proxies: Playwright takes HTTP(S) or SOCKSv5, with a username and password, for the whole browser or one context. One context per proxy keeps each IP with its own cookies.
- Patched browsers change the browser itself. Patchright is built to drop in where Playwright was, but it patches Chromium only. Camoufox works with Playwright too, but runs Firefox.
Pick the fix from the error page, not by trying all four.
Cloud browsers: what one browser hour costs
A cloud browser runs on someone else’s server. You connect Playwright to it over the network. Live list prices from each vendor’s own page, cheapest first:
| Vendor, plan it picks | Total a month | $/hr | Total a year | Free trial · note · source |
|---|---|---|---|---|
| Anchor BrowserPay as you go | $5.00 | $0.05 | $60 | docs.anchorbrowser.io · 29 Nov 2026 |
| Browser UsePay as you go | $6.00 | $0.06 | $72 | browser-use.com · 29 Nov 2026 |
| Cloudflare Browser RunPay as you go | $9.00 | $0.09 | $108 | developers.cloudflare.com · 29 Nov 2026 |
| SteelLaunch | $10 | $0.10 | $120 | $30 credits oncesteel.dev · 29 Nov 2026 |
| AgentQLPay as you go | $12 | $0.12 | $144 | agentql.com · 26 Nov 2026 |
| TinyFishPay as you go | $12 | $0.12 | $144 | tinyfish.ai · 26 Nov 2026 |
List prices from each vendor’s pricing page, US dollars before tax, live from our price data. Your own size, in the price calculator: Cloud browsers.
Free to start: Browserbase gives 1 hour, Cloudflare Browser Run 10 minutes a day, Hyperbrowser 5,000 credits, Steel a one-time credit.
Proxy traffic and CAPTCHA solves often cost extra. All of them side by side: cloud browsers.
Browser hours are the time a browser stays open, whether it’s loading or waiting. Close it when you’re done.
What else the pages charge for:
- Cloudflare bills Playwright sessions for hours and for browsers open at once. Workers Paid includes 10 at once (averaged over the month), then $2.00 per extra browser. Its own example: 50 hours in a month costs $3.60.
- Steel charges $10/GB for proxy traffic on Launch and $6/GB on Scale. The Scale plan includes $100 of usage a month.
- Hyperbrowser charges the same rates on every plan, including $10/GB for proxy data.
- Browserbase says 100 hours is roughly 3,000 page-level tasks. That is its own estimate, not our test.
Blocking images and fonts cuts the per-GB part of the bill.
Paste into your AI
I want to scrape this page: <URL>. The data I need: <fields>.
Before writing any browser code, help me check, in this order:
1. Is the data in the raw HTML? Tell me how to search the page source.
2. Is it JSON inside a <script> tag? If so, write Python with requests + re + json.
3. Does the Network tab (Fetch/XHR) show a JSON request with the data? Help me copy it
and write a Python requests loop with pagination.
Only if all three fail, write a Playwright script (Python or TypeScript) that:
- blocks images, fonts and media with page.route
- waits with locator.waitFor() on the first row, never waitForTimeout or networkidle
- prefers page.waitForResponse / expect_response to read the JSON over parsing HTML
- saves results to results.csv
If I get 403, 1020, "Just a moment" or a CAPTCHA, stop and tell me which error it is.
Why the prompt makes the AI go in that order: each step is cheaper than the next. Without an order, an AI may jump straight to a browser script. This prompt makes it rule out the cheap paths first.
Help it help you:
- Paste the HTML your script got, or the first 50 lines of it. The AI can’t open the page the way your code does.
- For step 3, paste the request you copied as cURL.
- Paste the full error text, not “it doesn’t work”.
Dev depth: headless modes and the cookie trick
Headless isn’t one thing. By default, headless Playwright runs the Chromium headless shell, a separate build. Google Chrome and Edge moved to a “new headless” mode that is closer to a normal window. Playwright warns that the two can behave differently. To run branded Chrome, launch with channel: 'chrome'.
Smaller installs. Only running headless, for example on a server? npx playwright install --with-deps --only-shell skips the full Chromium download.
Route patterns. page.route() takes a glob ('**/*.{png,jpg,jpeg}'), a RegExp or a function. context.route() applies the same rule to every page in the context, popups included.
Shared vs separate cookies. page.request and context.request share cookie storage with the browser context, both ways. Need a clean jar? request.newContext() makes one with its own cookies.
Find the API in code, not by eye. Log every response for one page load, then look for JSON:
page.on('response', r => {
if ((r.headers()['content-type'] ?? '').includes('json')) console.log(r.status(), r.url());
});
Related
Tools for this
| Tool | Price |
|---|---|
| $0.20/hr | |
| $0.15/hr | |
| Free | |
| $0.09/hr | |
| $0.10/1k req | |
| Free | |
| $0.10/hr | |
| Free | |
| Free | |
| Free | |
| Free | |
| Free | |
| $0.10/hr |
Sources
Playwright docs: Network (route, abort, waitForResponse, proxy) playwright.dev
Playwright for Python docs: Network (expect_response) playwright.dev
Playwright docs: Page (waitForSelector, waitForTimeout, networkidle: discouraged) playwright.dev
Playwright docs: Locator (waitFor, allInnerTexts, evaluateAll) playwright.dev
Playwright docs: API testing (context request shares cookies) playwright.dev
Playwright docs: Browsers (headless shell, new headless, channels) playwright.dev
Playwright docs: Library (install) playwright.dev
Playwright on GitHub (Apache-2.0 license) github.com
Playwright: Chromium, Firefox and WebKit, one API; JS/TS, Python, .NET, Java playwright.dev
Google Chrome Help: Keyboard shortcuts (view page source) support.google.com
Chrome DevTools: Network reference (Copy as cURL) developer.chrome.com
Chrome DevTools: View and change the DOM (Elements panel) developer.chrome.com
Patchright on GitHub: patched Playwright, drop-in, Chromium only github.com
Camoufox: open-source anti-detect browser built on Firefox camoufox.com
Camoufox docs: Usage (works with Playwright code) camoufox.com
Playwright for Python docs: Library (install) playwright.dev- Quotes to Scrape: JavaScript version (practice site) quotes.toscrape.com
- Quotes to Scrape: infinite scroll version (practice site) quotes.toscrape.com
- Quotes to Scrape: the JSON API behind the scroll page quotes.toscrape.com
HTTP Archive Web Almanac 2025: Page Weight almanac.httparchive.org
MDN: Navigator.webdriver developer.mozilla.org
Node.js: About (a JavaScript runtime environment) nodejs.org- npm: selenium-webdriver (official WebDriver JavaScript bindings) npmjs.com
Browserbase: Pricing browserbase.com
Steel: Pricing steel.dev
Hyperbrowser: Pricing hyperbrowser.ai
Cloudflare docs: Browser Run pricing developers.cloudflare.com