When a browser shows a list but a Python HTTP request returns an empty container, I first investigate the source of the records. Starting a browser is one possible answer, not the first diagnostic step.

Use Requests when an authorized data endpoint can provide the required records. Use Playwright when the permitted workflow needs browser execution or interaction. In both cases, define what a complete result looks like before adding pagination or concurrency.

This tutorial focuses on selecting that path and proving that one batch, then a bounded sequence of batches, contains the expected data. It uses Python 3 and illustrative endpoints. The examples have not been tested against a real target website; replace the addresses, fields and controls with those you have verified in an authorized environment. They are not production-ready scripts or evidence of a performance benchmark.

Start with a data contract, not a selector

A server can return a shell such as this:

<div id="results"></div>
<script src="/assets/app.js"></script>

The browser executes the script, which may request records and insert elements into the document. Requests retrieves an HTTP response; it does not execute the page's JavaScript. Passing that original response to an HTML parser cannot produce records that were never in it.

However, not every interactive page requires a browser for extraction. Some embed initial data in the document, while others load it through a separate request. Inspect the response before deciding which mechanism applies.

I would write down three requirements at this stage: the fields needed, the identifier used for deduplication, and the signal that means there are no more records. Without those, a script can run without errors and still deliver an incomplete dataset.

Observe two batches in the browser

Open the browser's Network panel, clear previous entries and select Fetch/XHR. Reload the page or activate its normal load-more control. Look for a response containing a title or identifier visible on the page.

Repeat the action once. Comparing requests for two batches is more informative than examining the first request alone.

Observation What it establishes
Method and endpoint Which operation delivers records
Query parameters or request body How filters and pagination are expressed
Response structure Where the records and continuation fields reside
Page number, offset or cursor What changes between successive batches
Authentication and session requirements Which authorized context the request depends on

If Fetch/XHR reveals nothing, inspect the original document and other request types. Some applications use WebSockets or already embedded data. An empty filter view does not mean there is no source to inspect.

Prefer an official API when one is available for the intended use. Seeing a request in developer tools does not itself authorize independent access, broader collection or bypassing access restrictions.

Requests: make cursor advancement explicit

Suppose your test endpoint returns the following contract:

{
  "items": [{"id": "a-101", "title": "Example article"}],
  "next_cursor": null
}

Here, a nonempty string in next_cursor means another batch is available, while JSON null means completion. Missing the field is an error, not an alternative completion signal. This is a teaching contract; another API may use different rules.

Install Requests:

python -m pip install requests

The following example tracks continuation tokens, deduplicates records and marks results as partial unless it reaches the documented completion signal:

import json
import time
from pathlib import Path

import requests

API_URL = "https://your-authorized-site.example/api/items"
MAX_BATCHES = 20
INTERVAL_SECONDS = 1.0

records = {}
seen_cursors = set()
cursor = None
completed = False

try:
    with requests.Session() as session:
        session.headers.update({
            "Accept": "application/json",
            "User-Agent": "LearningCrawler/1.0",
        })

        for batch_number in range(1, MAX_BATCHES + 1):
            params = {} if cursor is None else {"cursor": cursor}
            response = session.get(API_URL, params=params, timeout=15)
            response.raise_for_status()
            payload = response.json()

            if not isinstance(payload, dict):
                raise ValueError("Expected a JSON object")
            if not isinstance(payload.get("items"), list):
                raise ValueError("Expected an items list")
            if "next_cursor" not in payload:
                raise ValueError("Missing continuation field")

            for item in payload["items"]:
                if not isinstance(item, dict):
                    raise ValueError("Expected an item object")
                item_id = item.get("id")
                title = item.get("title")
                if not isinstance(item_id, str) or not item_id:
                    raise ValueError("Expected a nonempty string ID")
                if not isinstance(title, str) or not title.strip():
                    raise ValueError("Missing item title")
                records[item_id] = {"id": item_id, "title": title.strip()}

            next_cursor = payload["next_cursor"]
            print(f"Batch {batch_number}: {len(records)} unique records")

            if next_cursor is None:
                completed = True
                break
            if not isinstance(next_cursor, str) or not next_cursor:
                raise ValueError("Invalid continuation cursor")
            if next_cursor in seen_cursors:
                raise RuntimeError("Repeated cursor; stop to inspect pagination")

            seen_cursors.add(next_cursor)
            cursor = next_cursor
            if batch_number < MAX_BATCHES:
                time.sleep(INTERVAL_SECONDS)
finally:
    output = Path("items.json" if completed else "items.partial.json")
    output.write_text(
        json.dumps(list(records.values()), ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    print(f"Saved {len(records)} records to {output}")

if not completed:
    raise RuntimeError("Batch limit reached; results are partial")

The finally block saves accumulated records when an ordinary exception interrupts execution. It is not a checkpointing system and cannot protect against every process or machine failure. A new run also starts from the beginning and can overwrite these example filenames. Production recovery requires an explicit storage and checkpoint design.

The limits of 20 batches, 15 seconds and a one-second interval are illustrative settings. Follow the target's published access policy, and adjust the task budget to the permitted workload.

Requests documents two important distinctions: decoding JSON does not prove HTTP success, and its timeout is not a deadline for the complete response download or the entire collection job. Check status, business fields and overall completion separately. [1]

A valid empty batch with a new cursor may be meaningful under some API contracts; this example follows the continuation field. Conversely, a repeated cursor triggers a stop even if the response looks otherwise valid. Copy the actual endpoint's semantics rather than guessing them from field names.

If an authorized endpoint uses POST with a JSON body, Requests supports json=; form data uses data=. Verify the request format before changing the method. Do not blindly copy browser credentials or all request headers into shared code.

Playwright: wait for the response caused by the action

A browser is useful when the permitted workflow requires page initialization or user interaction. Install both the Python package and the browser binary:

python -m pip install playwright
python -m playwright install chromium

Playwright provides synchronous and asynchronous APIs. The following uses its synchronous API for a small, sequential example. [2]

Assume the authorized test page has a button labeled Load more that requests /api/items?page=2. This example captures that one batch; it is not a complete pagination loop:

import json
from pathlib import Path
from urllib.parse import parse_qs, urlsplit

from playwright.sync_api import sync_playwright

PAGE_URL = "https://your-authorized-site.example/items"
API_HOST = "your-authorized-site.example"


def matches_next_batch(response):
    url = urlsplit(response.url)
    return (
        url.scheme == "https"
        and url.netloc == API_HOST
        and url.path == "/api/items"
        and parse_qs(url.query).get("page") == ["2"]
        and response.request.method == "GET"
    )


with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    try:
        page = browser.new_page()
        page.set_default_timeout(15_000)
        navigation = page.goto(PAGE_URL, wait_until="domcontentloaded")
        if navigation is None or not navigation.ok:
            raise RuntimeError("Page navigation failed")

        with page.expect_response(matches_next_batch, timeout=15_000) as pending:
            page.get_by_role("button", name="Load more", exact=True).click()

        response = pending.value
        if not response.ok:
            raise RuntimeError(f"Batch request failed: HTTP {response.status}")

        payload = response.json()
        if not isinstance(payload, dict) or not isinstance(payload.get("items"), list):
            raise ValueError("Unexpected batch structure")

        Path("browser-batch.json").write_text(
            json.dumps(payload["items"], ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
        print(f"Captured {len(payload['items'])} items")
    finally:
        browser.close()

Register the response wait before clicking. If the listener is installed afterward, a fast response can already have occurred. Playwright's network documentation demonstrates wrapping the triggering action in expect_response(). [3]

Match the endpoint and relevant parameters precisely. A predicate that accepts any URL containing api may capture analytics or unrelated recommendations. If the real endpoint uses a POST body or a cursor, change the matching logic accordingly.

The page must also be ready to process the interaction. Playwright's actionability checks do not prove that every application event handler has been attached. Its navigation documentation discusses hydration cases where an apparently enabled control does not yet perform the intended action. [4]

Distinguish response readiness from rendered-list readiness

Receiving the correct JSON is sufficient if the goal is to save that response. It is not proof that the browser has finished updating the visible list.

If the deliverable is rendered text, wait for a condition that identifies the relevant batch in the page: a known record ID, an expected count under a stable contract, or a completed-loading marker. The first visible item only proves that one item is visible.

Playwright explicitly notes that locator.all() returns current matches without waiting for the list to finish loading. Calling it immediately can produce an incomplete snapshot. [5]

Fixed sleeps are a weak substitute for such conditions. A five-second delay means time has passed; it does not establish that a specific response was successful or that all records have rendered. This is different from the deliberate request interval in the Requests example, which controls pacing rather than proving readiness.

For infinite scrolling, inspect the requests triggered by scrolling before building a loop. A virtualized list may retain only visible items in the DOM. Reading the DOM once at the end can therefore miss earlier batches even after extensive scrolling.

Verify completion before increasing throughput

A useful acceptance record separates transport, structure and completeness:

Layer Evidence to retain
HTTP response Status and sanitized error context
Data structure Expected fields and valid record identifiers
Pagination Continuation progress and the actual end condition
Output Unique records saved and any partial-result status
Browser interaction The action and the matching batch it produced

Deduplication removes repeated identifiers; it does not prove that no records were missed. A changing dataset can move between pages during collection. Record the collection window and any snapshot guarantees the API actually provides, rather than claiming a perfect historical snapshot from a simple pagination loop.

When a browser succeeds but a script fails, compare authorized session and request conditions. HTTP cookies can carry website session state independently of the proxy account.

If work queues up as you add jobs, distinguish proxy concurrency from requests per second, and distinguish local pool waiting from a proxy timeout. More workers do not automatically produce more validated records.

A proxy can change the outbound path. It does not execute JavaScript for Requests, correct a cursor, or turn a login page into the intended JSON response.

FAQ

Can BeautifulSoup extract dynamically loaded content?

It can parse HTML supplied to it, including HTML obtained after browser rendering. It does not execute page scripts itself, so changing the parser cannot recover data absent from the supplied document.

Should I always choose Playwright for a JavaScript-heavy site?

No. First determine whether the required data is already embedded or available through an authorized endpoint. Browser automation is appropriate when the actual workflow needs browser behavior, not simply because the site uses JavaScript.

Why does an HTTP 200 response still fail the collection task?

It can contain a login page, a business error or fields that do not satisfy the expected contract. Verify the response structure and the intended records in addition to the HTTP status.

Can I calculate the next cursor myself?

Only if the API explicitly documents that behavior. Treat opaque cursors as returned continuation tokens; do not invent replacements. Stop and investigate repeated or invalid tokens.

What should I do when access is challenged or restricted?

Stop automatic retries and review authorization, supported APIs and rate limits. Switching exits is not a substitute for resolving an access restriction.

I would consider the first milestone complete only when one authorized batch can be explained, validated and saved. Then add continuation handling. Increase concurrency after the job can distinguish a complete result from a partial one.

References

Documentation reviewed on November 19, 2026. Endpoint names, response fields and timing values are instructional examples.

  1. Requests: Quickstart
  2. Playwright Python: Getting started — Library
  3. Playwright Python: Network
  4. Playwright Python: Navigations
  5. Playwright Python: Locator

About the author

Written by LeoCrawls.