Skip to content
GUIDE

How to Scrape JavaScript Websites with Python and Node.js

Why requests and BeautifulSoup return an empty page on dynamic sites, how to find the JSON the page loads (often the best option), and how to render with Playwright or Puppeteer when you must: waits, infinite scroll, speed and manners. Every example runs against a public practice site.

Last updated

Short answer

requests and BeautifulSoup only see the HTML the server sends. On a JavaScript website the browser adds the content later, so your selectors match nothing. First look for the data as JSON, in a script tag or from the page's API. If there isn't any, render the page with Playwright or Puppeteer, wait for the content, then parse it.

Every example below runs against quotes.toscrape.com, a practice site made by Zyte for exactly this. Its /js/ page builds the quotes with JavaScript and its /scroll page loads them with infinite scroll, which covers the two cases that break most scrapers. We ran all of the code in November 2026; the numbers in the comments are what it printed.

Why requests and BeautifulSoup return an empty page

empty.py
import requests
from bs4 import BeautifulSoup

resp = requests.get("https://quotes.toscrape.com/js/", timeout=20)
soup = BeautifulSoup(resp.text, "html.parser")

print(resp.status_code)               # 200
print(len(soup.select("div.quote")))  # 0: the quotes don't exist in this HTML

The request succeeded and the HTML parsed, but there are no quotes in it. The server sent a page skeleton plus JavaScript, and the browser builds the quotes after the page loads. BeautifulSoup is an HTML parser, not a browser: it never runs that JavaScript, so it can't see anything the JavaScript creates. No BeautifulSoup option changes that.

How to tell whether a site renders client-side:

  • Compare View Source (the HTML the server sent) with the browser's Elements panel (the live DOM). If the content is in Elements but not in View Source, it's rendered by JavaScript.
  • Search the raw response for a phrase you can see on the page: curl -s URL | grep "some visible text". No match means rendering.
  • Disable JavaScript in DevTools (Command menu, “Disable JavaScript”) and reload. Whatever disappears is what requests can't see.

Four ways to scrape a dynamic website

ApproachUse it whenSpeed and costBreaks when
Embedded JSON in the HTMLThe page ships its data in a <script> (__NEXT_DATA__, JSON-LD, a JS variable)As fast as a normal requestThe site changes its framework or data shape
The page's own JSON APIThe Network tab shows XHR or fetch calls returning the dataFastest; paginated, structured, smallThe API needs tokens or signed parameters, or changes without notice
Headless browser (Playwright, Puppeteer)Data only exists after rendering or interactionSeconds per page; hundreds of MB of RAM per browserSelectors change; the site detects automation
Rendering API (e.g. RenderKit)You want rendered HTML or markdown without running browsersOne HTTP call; billed per pagePages need clicks or scrolling the API doesn't do

Work down the table. The first two options skip rendering entirely, and when they work they're faster and far more reliable than any browser automation.

Option 1: Find the JSON behind the page

Data embedded in the HTML

Many JavaScript sites send their data inside the HTML and build the page from it in the browser. On /js/, it's a JavaScript array in a <script> tag, which happens to be valid JSON:

embedded_json.py
import json
import re

import requests

html = requests.get("https://quotes.toscrape.com/js/", timeout=20).text

# The data ships inside the page as a JavaScript array; the browser builds the HTML from it.
match = re.search(r"var data = (\[.*?\]);", html, re.DOTALL)
quotes = json.loads(match.group(1))

print(len(quotes), "quotes")
for q in quotes[:3]:
    print(q["author"]["name"], "-", q["text"])

Two patterns are common enough to check on every site. Next.js sites using the pages router put the page's props in a <script id="__NEXT_DATA__"> tag, and many sites publish Schema.org data for products, articles and events as JSON-LD:

next_data.py
import json

import requests
from bs4 import BeautifulSoup

html = requests.get("https://shop.example.com/products/blue-mug", timeout=20).text
soup = BeautifulSoup(html, "html.parser")

# Next.js (pages router): the page's props, as JSON
next_data = soup.find("script", id="__NEXT_DATA__")
if next_data:
    props = json.loads(next_data.string)["props"]["pageProps"]

# Schema.org JSON-LD: products, articles, events, breadcrumbs
for tag in soup.find_all("script", type="application/ld+json"):
    print(json.loads(tag.string))
  • Search View Source for a value you can see on the page, such as a price or a name. If it appears inside a <script>, you've found the data.
  • No __NEXT_DATA__ on a Next.js site usually means it uses the newer app router, which streams data in a format that's harder to parse. There, the API route is often the better target.
  • Embedded JSON usually carries more than the page shows, such as IDs, SKUs and timestamps, which is a bonus when you need clean data.

Call the XHR or fetch API directly

If the data isn't in the HTML, the page fetches it. Open DevTools, go to the Network tab, filter by Fetch/XHR, then reload, scroll or click whatever loads more content. On /scroll, each batch comes from /api/quotes?page=N, and the response says whether there's another page. Right-click a request and choose Copy as cURL to see the exact headers it sent.

json_api.py
import time

import requests

session = requests.Session()
session.headers["User-Agent"] = "quotes-research/1.0 (+https://example.com/contact)"

quotes, page = [], 1
while True:
    resp = session.get(
        "https://quotes.toscrape.com/api/quotes", params={"page": page}, timeout=20
    )
    resp.raise_for_status()
    data = resp.json()
    quotes.extend(data["quotes"])
    if not data["has_next"]:
        break
    page += 1
    time.sleep(1)  # one request per second

print(len(quotes), "quotes from", page, "pages")
print(quotes[0]["author"]["name"], quotes[0]["tags"])
  • This is usually the best way to scrape a JavaScript website: one small JSON response per page instead of a browser rendering HTML, images and scripts.
  • Some APIs need headers the browser sends, such as a CSRF token, a cookie or an API key embedded in the page. Copy them from the cURL command, and expect short-lived tokens to need refreshing.
  • An undocumented API isn't a contract and can change any time. Check the site's terms, and use the official API if there is one.
  • Keep the delay. An API that's easy to call is just as easy to overload.

Option 2: Render the page with Playwright and parse it with BeautifulSoup

When the data only exists after the page runs, use a real browser. Playwright drives headless Chromium, Firefox or WebKit from Python. Load the page, wait until the content exists, take the rendered HTML, and keep using the BeautifulSoup code you already know:

playwright_bs4.py
# pip install playwright beautifulsoup4 && playwright install chromium
from bs4 import BeautifulSoup
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()  # headless by default
    page = browser.new_page()
    page.goto("https://quotes.toscrape.com/js/")
    page.wait_for_selector("div.quote")  # wait until JavaScript has rendered them
    html = page.content()  # the rendered DOM, not the original source
    browser.close()

soup = BeautifulSoup(html, "html.parser")
for quote in soup.select("div.quote"):
    author = quote.select_one("small.author").get_text()
    text = quote.select_one("span.text").get_text()
    print(f"{author}: {text}")
  • page.content() returns the live DOM serialized as HTML, which is what View Source would show if it ran the JavaScript.
  • You can skip BeautifulSoup and use Playwright's locators: page.locator("div.quote span.text").all_inner_texts() returns the same strings, and locators wait for elements before acting on them.
  • Use the async API (playwright.async_api) when you scrape many pages concurrently; the sync API is simpler for scripts.
  • Prefer Selenium? The same pattern works: load the page, wait with WebDriverWait, then pass driver.page_source to BeautifulSoup.

Wait for the right thing

Most flaky scrapers wait for the wrong event. page.goto() returns when the load event fires, which on a JavaScript site is often before the data has arrived.

Wait strategyPlaywright (Python)Verdict
For the element that holds the datapage.wait_for_selector("div.quote")Best default: you wait exactly as long as needed
For a condition in the pagepage.wait_for_function("...", arg=..., timeout=...)Counts, text changes, "more items than before"
For a specific API responsewith page.expect_response(...)When you also want the JSON itself
Until the network is quietpage.goto(url, wait_until="networkidle")Playwright's docs mark it discouraged; pages that poll never go quiet
A fixed sleeppage.wait_for_timeout(3000)Too slow when the page is fast, too short when it's slow

Infinite scroll

Infinite-scroll pages load the next batch when you reach the bottom. Scroll, wait until more items exist than before, and stop when nothing new arrives. Listening to responses at the same time hands you the underlying JSON, which is often a sign you should switch to calling the API directly:

infinite_scroll.py
from playwright.sync_api import TimeoutError as PlaywrightTimeout
from playwright.sync_api import sync_playwright

captured = []  # the JSON the page fetches while we scroll


def on_response(response):
    if "/api/quotes" in response.url and response.ok:
        captured.append(response.json())


with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.on("response", on_response)
    page.goto("https://quotes.toscrape.com/scroll")
    page.wait_for_selector("div.quote")

    while True:
        count = page.locator("div.quote").count()
        page.mouse.wheel(0, 20000)  # scroll to the bottom to trigger the next batch
        try:
            page.wait_for_function(
                "n => document.querySelectorAll('div.quote').length > n",
                arg=count,
                timeout=5000,
            )
        except PlaywrightTimeout:
            break  # nothing new for 5 seconds: end of the feed

    texts = page.locator("div.quote span.text").all_inner_texts()
    browser.close()

api_quotes = sum(len(r["quotes"]) for r in captured)
print(len(texts), "quotes in the DOM,", api_quotes, "in the captured JSON")
  • mouse.wheel() doesn't wait for scrolling or loading to finish, so the loop waits on a condition: more div.quote elements than before.
  • The stop rule is “nothing new for 5 seconds”, not a fixed number of scrolls. On this site the page keeps requesting pages past the end (we saw requests for pages 11 to 14, which came back empty), so counting what's actually in the DOM is more reliable than counting requests.
  • Pages that replace items as you scroll (virtualized lists) only keep a window of items in the DOM. Collect items on every iteration instead of once at the end, or use the API.

Make it faster: block images, fonts and media

A scraper rarely needs images, fonts or video, and they're most of a page's bytes. Abort those requests and keep everything the page needs to run:

block_resources.py
from playwright.sync_api import sync_playwright

SKIP = {"image", "media", "font"}  # keep scripts, XHR and CSS: the page needs those

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.route(
        "**/*",
        lambda route: route.abort()
        if route.request.resource_type in SKIP
        else route.continue_(),
    )
    page.goto("https://quotes.toscrape.com/js/")
    page.wait_for_selector("div.quote")
    print(page.locator("div.quote").count(), "quotes")
    browser.close()

Scrape a website with Node.js

fetch and Cheerio see the same empty page

Node's equivalent of requests and BeautifulSoup is fetch plus Cheerio, and it has the same blind spot:

empty.mjs
import * as cheerio from "cheerio";

const res = await fetch("https://quotes.toscrape.com/js/");
const $ = cheerio.load(await res.text());

console.log(res.status);            // 200
console.log($("div.quote").length); // 0

For static pages, fetch and Cheerio are the right tools: fast, light and simple. For JavaScript-rendered pages, the same advice applies as in Python: look for embedded JSON or the API first, then render.

Puppeteer: render, wait, extract, paginate

Puppeteer is a Node library for controlling Chrome (and Firefox). This scraper renders each page of /js/, extracts the quotes in the browser with $$eval, and follows the Next link until there isn't one:

puppeteer_scraper.mjs
// npm i puppeteer  (downloads a matching Chrome for Testing build)
import puppeteer from "puppeteer";

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent("quotes-research/1.0 (+https://example.com/contact)");

const quotes = [];
let url = "https://quotes.toscrape.com/js/";

while (url) {
  await page.goto(url, { waitUntil: "domcontentloaded" });
  await page.waitForSelector("div.quote"); // rendered by JavaScript after load

  const batch = await page.$$eval("div.quote", (els) =>
    els.map((el) => ({
      text: el.querySelector("span.text").textContent,
      author: el.querySelector("small.author").textContent,
      tags: [...el.querySelectorAll("a.tag")].map((a) => a.textContent),
    })),
  );
  quotes.push(...batch);

  // Follow the "Next" link until there isn't one.
  url = await page.$eval("li.next a", (a) => a.href).catch(() => null);
  if (url) await new Promise((resolve) => setTimeout(resolve, 1000));
}

console.log(quotes.length, "quotes");
console.log(quotes[0]);
await browser.close();
  • $$eval runs your function inside the page and returns plain data, so you extract in one round trip instead of fetching element handles one by one.
  • page.goto waits for load by default. domcontentloaded returns sooner, and waitForSelector then waits for the content itself.
  • $eval throws when nothing matches, which is why the Next-link lookup ends in .catch(() => null).
  • npm i puppeteer downloads a matching Chrome for Testing build. Use puppeteer-core with your own Chrome when you can't download one, for example in a slim Docker image.

Playwright for Node.js: infinite scroll

playwright_scroll.mjs
// npm i playwright && npx playwright install chromium
import { chromium } from "playwright";

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto("https://quotes.toscrape.com/scroll");
await page.waitForSelector("div.quote");

while (true) {
  const count = await page.locator("div.quote").count();
  await page.mouse.wheel(0, 20000); // scroll to the bottom to load the next batch
  try {
    await page.waitForFunction(
      (n) => document.querySelectorAll("div.quote").length > n,
      count,
      { timeout: 5000 },
    );
  } catch {
    break; // nothing new for 5 seconds: end of the feed
  }
}

const quotes = await page.locator("div.quote span.text").allInnerTexts();
console.log(quotes.length, "quotes");
await browser.close();

Puppeteer or Playwright?

PuppeteerPlaywright
LanguagesJavaScript and TypeScriptJavaScript/TypeScript, Python, Java, .NET
BrowsersChrome and FirefoxChromium, Firefox and WebKit
Browser installDownloaded by npm i puppeteernpx playwright install chromium
WaitingExplicit waitForSelector, waitForResponseSame, plus locators that wait before acting
Pick it whenYou're Node-only and Chrome-onlyYou want one API across languages and browsers

Both are solid choices for headless Chrome web scraping. The bigger differences are in the code you write around them: waiting on the right signal, reusing browsers, and handling failures.

Headless Chrome web scraping at scale

  • Reuse the browser. Launching Chromium takes far longer than opening a tab. Launch once, open a new page (or a new context, for isolated cookies) per URL, and close pages when you're done with them.
  • Cap concurrency. Every open page needs its own renderer memory. Run a fixed number of pages at a time and queue the rest; why Puppeteer eats RAM explains where the memory goes.
  • Set timeouts and retry with backoff. Pages hang, and browsers occasionally crash. Treat both as normal events, not surprises.
  • Containers need care. Chromium in Docker needs the right system libraries and enough shared memory; see headless Chrome in Docker.
  • Don't render what you don't need. Block heavy resources, and use the JSON API wherever one exists.

Rate limits, robots.txt and ethics

  • Check robots.txt before you crawl, with your own user agent. A 4xx response for robots.txt means no rules; a 5xx means assume everything is disallowed. Web scraping for LLMs has working robots.txt code for Python and Node.
  • One request at a time per site with a delay, about a second unless robots.txt sets a Crawl-delay. Back off on 429 and 503 responses and honour Retry-After.
  • Identify yourself with a user agent that includes a way to contact you, and cache responses so you don't fetch the same page twice.
  • Read the terms of service, don't scrape behind a login without permission, and don't collect personal data you don't need.

When a site blocks headless browsers

Some sites use bot protection that challenges automated browsers. The symptoms are a 403 or 429, an empty body, or a 200 response whose page says “Just a moment”, “Checking your browser” or “Verify you are human”. Slowing down, using an honest user agent, and asking the site for API access or a data feed are the legitimate fixes. Stealth plugins and CAPTCHA-solving services exist to defeat protections a site deliberately chose, and that's both an arms race and often a terms-of-service violation.

Rendered HTML from an API: RenderKit /v1/extract

If you'd rather not run and patch browsers, RenderKit renders the page in Chromium and returns the result in one request. With format: "html" you get the rendered DOM with scripts, styles and forms stripped and class attributes intact, so your existing BeautifulSoup or Cheerio selectors keep working. With format: "markdown" you get clean main-content markdown for an LLM instead.

POSTextract.sh
curl https://api.renderkit.tech/v1/extract \
  -H "x-api-key: $RENDERKIT_API_KEY" \
  -H "content-type: application/json" \
  -d '{
    "url": "https://quotes.toscrape.com/js/",
    "format": "html",
    "only_main_content": false,
    "wait_for_selector": "div.quote"
  }'
renderkit_bs4.py
# pip install renderkit-sdk beautifulsoup4
import os

from bs4 import BeautifulSoup
from renderkit import RenderKit

rk = RenderKit(os.environ["RENDERKIT_API_KEY"])

doc = rk.extract(
    url="https://quotes.toscrape.com/js/",
    format="html",                  # the rendered DOM; scripts, styles and forms removed
    only_main_content=False,        # keep the whole <body>, class attributes intact
    wait_for_selector="div.quote",  # 422 SELECTOR_NOT_FOUND if it never appears
)
if doc["meta"].get("blocked"):
    raise RuntimeError("Got a bot-check page instead of the content")

soup = BeautifulSoup(doc["content"], "html.parser")
for quote in soup.select("div.quote"):
    author = quote.select_one("small.author").get_text()
    text = quote.select_one("span.text").get_text()
    print(f"{author}: {text}")
renderkit_cheerio.mjs
// npm i renderkit-sdk cheerio
import * as cheerio from "cheerio";
import { RenderKit } from "renderkit-sdk";

const rk = new RenderKit(process.env.RENDERKIT_API_KEY);

const doc = await rk.extract({
  url: "https://quotes.toscrape.com/js/",
  format: "html",
  only_main_content: false,
  wait_for_selector: "div.quote",
});
if (doc.meta.blocked) throw new Error("Got a bot-check page instead of the content");

const $ = cheerio.load(doc.content);
const quotes = $("div.quote")
  .map((_, el) => ({
    text: $(el).find("span.text").text(),
    author: $(el).find("small.author").text(),
  }))
  .get();
console.log(quotes);
  • only_main_content: false keeps the whole <body>, including navigation and footers; the default (true) returns just the main content block.
  • wait_for_selector waits for your element after the page loads. If it never appears, the request fails with 422 SELECTOR_NOT_FOUND instead of returning the wrong page, and failed renders are refunded.
  • When the site serves a bot-check page instead of content, the response includes meta.blocked: true. RenderKit doesn't solve CAPTCHAs.
  • The extract endpoint doesn't click or scroll for you. For infinite feeds, call the JSON API or use Playwright as shown above.
  • Each extract costs 1 credit, cache hits cost 0, and the free trial includes 500 credits for 14 days with no card.

More on the markdown side: URL to Markdown API and the extract reference.

Feed scraped pages to a model: web scraping for LLMs and RAG. Convert what you scrape: HTML to markdown in Python and Node. Run browsers in containers: headless Chrome in Docker. Capture pages as images: Playwright screenshots and Puppeteer screenshots.

Common questions

Not on its own. BeautifulSoup parses the HTML it is given and never runs JavaScript, so content the browser adds after loading is invisible to it. Either find the data as JSON (embedded in a script tag or returned by the page's API), or render the page with Playwright or Selenium and pass the rendered HTML to BeautifulSoup.

Check the Network tab in DevTools for XHR or fetch requests that return the data and call that API with requests. If there is none, use Playwright: load the page, wait for the element that holds the data with wait_for_selector, then read page.content() into BeautifulSoup or use Playwright's locators directly.

For static pages, use fetch to download the HTML and Cheerio to query it with CSS selectors. For JavaScript-rendered pages, look for the JSON API first, then use Puppeteer or Playwright: open the page, wait for the content selector, and extract with page.$$eval or Playwright locators.

Both work well. Puppeteer is Node-only and focused on Chrome, and installs a matching Chrome for you. Playwright supports Python, Java and .NET as well as Node, drives Chromium, Firefox and WebKit, and its locators wait for elements automatically. If you might want Python or several browsers later, choose Playwright.

First check whether the scroll loads data from an API you can call directly with a page parameter. If not, use a headless browser: scroll to the bottom, wait until there are more items than before, and stop when nothing new appears for a few seconds. For virtualized lists, collect items on every scroll because old ones are removed from the page.

Open DevTools, select the Network tab, filter by Fetch/XHR, and reload or scroll the page. Click requests to see which one returns the data you want as JSON, then right-click it and copy it as cURL to see the URL, parameters and headers it needs.

Selenium works: load the page, wait with WebDriverWait for the element you need, and hand driver.page_source to BeautifulSoup. Many new projects pick Playwright because its waiting is built in and its setup is simpler, but if you already run Selenium there is no need to switch just for scraping.

Sites with bot protection look at request rate, IP reputation and browser fingerprints, and serve a challenge page or an error to traffic that looks automated. Slow down, identify your scraper honestly, cache instead of re-fetching, and ask the site for API access if you need the data regularly. Defeating CAPTCHAs usually breaks the site's terms.

Ship your first render in 60 seconds.

500 free credits to start. No card. Cancel by ignoring it.

Get your free key$npm i renderkit-sdk