Pagination in Web Scraping: How to Collect Data Across Pages
TL;DR
Pagination in web scraping means following a site's continuation mechanism until you reach an explicit stopping condition or a defined collection budget.
Follow an HTML next link or a documented API cursor instead of assuming every website accepts a predictable page number.
Commit records and the continuation checkpoint together so a restart does not silently skip a page.
Deduplicate records by a stable source identifier, and detect repeated page content separately to catch navigation loops.
Infinite scroll is an interaction pattern; the data may arrive through a paginated response, and the browser still needs a measurable progress signal.
Nstdata Crawl can discover and collect a bounded set of linked pages, but a crawl page limit does not guarantee complete coverage of a site's catalog.
What does pagination mean in web scraping?
Pagination in web scraping is the process of collecting a dataset spread across multiple pages or responses while preserving its continuation state.
Consider a catalog showing 20 products per page. Downloading its first page successfully gives you 20 records, not the catalog. A reliable scraper must find the next location, collect its records, detect whether anything new arrived, and remember where to resume after a failure.
The central problem is completeness. Managed collection through Nstdata Crawl can supply page artifacts, but the dataset still needs a defined completeness contract. A job can finish without an exception while missing pages, collecting the same page repeatedly, or combining records from inconsistent snapshots. This guide therefore emphasizes bounded collection and durable checkpoints. For browser interaction patterns, the separate guide to handling pagination and infinite scroll provides complementary context.
Which pagination pattern should you follow?
Follow the continuation mechanism actually returned by the source, because page numbers, offsets, cursors, and scrolling have different failure modes.
An opaque cursor belongs to the query that produced it. Preserve the sort order, filters, and access context associated with that query. Incrementing a cursor as though it were a page number is not a supported shortcut.
A server may return a complete next URL in a response header. The GitHub REST pagination documentation illustrates following the Link header's next relation. That pattern is useful evidence of a continuation contract; it does not mean an unrelated retailer exposes the same API.
What should you prepare before collecting multiple pages?
Prepare an authorized source, a stable record key, a collection budget, and a persistent checkpoint before increasing the page count.
For the Python example, use Python 3.11 or later, Requests, Beautiful Soup, and the standard-library SQLite module. The Books to Scrape practice site supplies the target. Its product values are demonstration data, so this example extracts titles and URLs rather than treating prices as market observations.
Starting URL: catalog page 48, allowing a small demonstration near the end.
Per-run budget: two pages, so the first run intentionally stops before completion.
Record key: the resolved product URL for this particular demo.
Checkpoint: the next URL stored in the same database as the records.
Acceptance rule: every card must contain a title and an allowed product URL.
A product URL is not universally a stable business identifier. Variants, tracking parameters, and redirects can create several URLs for one item. Prefer a documented immutable source ID when it exists; keep the raw source URL for provenance even after normalization.
How can you follow next links and resume safely?
You can follow HTML next links safely by validating each response and committing the new records together with the next-page checkpoint.
Method 1: Collect HTML pages with a durable checkpoint
Use this method when the needed cards and continuation link are present in the returned HTML. It avoids adding a browser when the source does not require one.
Step 1: Install the dependencies
Run this inside your Python virtual environment:
python -m pip install requests beautifulsoup4
The script uses an explicit connect/read timeout and refuses redirects so an unexpected redirect cannot silently change the allowed collection destination. Production workflows may follow verified redirects, but should validate each hop rather than only inspecting the final URL afterward.
Step 2: Save the collector
Save this as collect_pages.py:
import hashlib
import json
import os
import sqlite3
from datetime import datetime, timezone
from urllib.parse import urljoin, urlsplit
import requests
from bs4 import BeautifulSoup
SEED ='https://books.toscrape.com/catalogue/page-48.html'LIMIT =2DB = os.environ.get('PAGINATION_DB','books.sqlite')defallowed(url): parts = urlsplit(url)return parts.scheme =='https'and parts.netloc =='books.toscrape.com'with sqlite3.connect(DB)as db, requests.Session()as session: db.execute('CREATE TABLE IF NOT EXISTS records (url TEXT PRIMARY KEY, title TEXT, observed_at TEXT)') db.execute('CREATE TABLE IF NOT EXISTS state (id INTEGER PRIMARY KEY, next_url TEXT)') db.execute('CREATE TABLE IF NOT EXISTS pages (fingerprint TEXT PRIMARY KEY, url TEXT)') db.execute('INSERT OR IGNORE INTO state VALUES (1, ?)',(SEED,)) db.commit() visited =0while visited < LIMIT: current = db.execute('SELECT next_url FROM state WHERE id=1').fetchone()[0]if current isNone:breakifnot allowed(current):raise ValueError('Next URL left the allowed origin') response = session.get(current, timeout=(10,30), allow_redirects=False) response.raise_for_status()if response.status_code !=200:raise ValueError('Unexpected page status; review redirect or response') soup = BeautifulSoup(response.content,'html.parser') cards = soup.select('article.product_pod h3 a')ifnot cards:raise ValueError('No product cards; do not advance checkpoint') rows =[(urljoin(current, c['href']), c.get('title','').strip())for c in cards]ifany(not title ornot allowed(url)for url, title in rows):raise ValueError('Invalid product record') fingerprint = hashlib.sha256('\n'.join(sorted(url for url, _ in rows)).encode()).hexdigest()if db.execute('SELECT 1 FROM pages WHERE fingerprint=?',(fingerprint,)).fetchone():raise ValueError('Repeated page content; review pagination before continuing') link = soup.select_one('li.next a') next_url = urljoin(current, link['href'])if link elseNoneif next_url isnotNoneandnot allowed(next_url):raise ValueError('Next URL left the allowed origin') observed = datetime.now(timezone.utc).isoformat()with db: db.executemany('INSERT OR REPLACE INTO records VALUES (?, ?, ?)',[(u, t, observed)for u, t in rows]) db.execute('INSERT INTO pages VALUES (?, ?)',(fingerprint, current)) db.execute('UPDATE state SET next_url=? WHERE id=1',(next_url,)) visited +=1 next_url = db.execute('SELECT next_url FROM state WHERE id=1').fetchone()[0]print(json.dumps({'pages_this_run': visited,'records_total': db.execute('SELECT COUNT(*) FROM records').fetchone()[0],'next_url': next_url,'complete': next_url isNone}))
The transaction matters more than the file format. If validation fails, the program never advances the checkpoint. If the database transaction fails, both record writes and the checkpoint update roll back together. SQLite's connection transaction behavior documents the context manager used here.
The page fingerprint is a separate safeguard from record deduplication. A unique product key prevents duplicate stored records, while a fingerprint detects a server repeatedly serving the same set of cards under different next URLs. Neither proves that all expected products were returned.
Step 3: Run and resume the collector
Run python collect_pages.py, then run it again using the same working directory so both executions open the same database.
The first run in this walkthrough collected two pages, stored 40 distinct product URLs, and left page 50 as its next checkpoint. The second run collected one additional page, reached 60 stored records, and reported complete: true. A third execution reported zero new pages and retained those 60 records.
That result verifies resumption over the three-page demonstration range. It does not claim to have collected the full practice catalog, and it is not a benchmark of another site's pagination behavior.
Step 4: Inspect the saved state
Open books.sqlite with a SQLite client and inspect records, pages, and state. Check that every record has a nonempty title, that state.next_url is null after completion, and that the page table contains three distinct fingerprints.
The collector is designed for one worker. Sharing this checkpoint between independent workers requires a claim or lease mechanism; starting several copies is not a distributed scheduler. Start a fresh job state when intentionally recrawling the same range, and preserve the earlier observations if you need historical comparison.
How should you handle cursors and infinite scroll?
Handle cursors as opaque continuation tokens and infinite scroll as an interaction that must produce measurable progress.
Method 2: Follow a documented API continuation
Use an API when the site provides authorized, documented access to the required dataset. It can provide clearer identifiers and end conditions than a rendered list.
Step 1: Keep the query contract fixed
Record the endpoint, filters, ordering, and page size alongside the job. Check the API's documentation for cursor expiry, snapshot semantics, and rate limits. A response obtained with different filters should not overwrite the original checkpoint.
Step 2: Commit records before advancing the cursor
Apply the same transaction principle as the HTML example: store validated records and the returned next token together. If the API says the cursor expired, restart or recover according to its documented behavior. Do not silently substitute a guessed offset.
Step 3: Test for progress and completion
Track unique record count, response count, and repeated tokens. An empty batch is terminal only if the source contract defines it that way. Some APIs can return an empty intermediate page with a valid continuation token.
Method 3: Advance a browser-controlled list
Use a browser when an authorized interaction is necessary and no suitable documented API is available.
Step 1: Identify the progress signal
Choose the record container, stable record identity, load-more control, and visible end marker. A page's pixel height is a weak signal because lazy-loaded images, ads, and virtualized lists can change it independently of records.
Step 2: Perform one continuation action
Click once or scroll once, then wait for a new record identity or the relevant response. Store newly observed records before the list recycles its DOM nodes. Set a maximum action count and a time budget.
Step 3: Classify the stopping reason
Record whether the source explicitly ended, the budget was exhausted, or progress stalled. These are different outcomes. A stalled page should become a diagnostic task rather than a falsely successful dataset. Browser ownership and managed collection are compared in Web Scraping API vs Playwright.
How can Nstdata Crawl collect a bounded set of website pages?
Nstdata Crawl is a Web Crawling API for LLM-ready data that can discover and retrieve linked website pages within explicit scope limits.
Method 4: Use managed collection for linked-page datasets
This method fits documentation, reference pages, and other permitted linked content when your application needs page artifacts. It does not promise that every target's load-more button will be pressed or every private cursor discovered.
Site discovery and recursive crawling: bound exploration by page count and depth; review discovered URLs against the intended scope.
JavaScript rendering: wait for relevant page content when basic HTML is insufficient.
API and MCP access: submit work, inspect task status, retrieve pages, and read returned content references in a workflow.
Six output formats: Markdown for text processing, HTML for parsing, links for discovery, PDF and screenshot for review, and rawData for supported raw output. Business records still require a validated extraction layer.
Built-in managed access: standard managed collection does not require separately configuring proxy host, port, username, or password.
Configure the official hosted endpoint, https://mcp.nstdata.io/crawl, in an MCP client using the authentication instructions in the Nstdata Crawl MCP integration guide. Keep the API key outside prompts and source files.
Step 2: Give the assistant explicit limits
Use this instruction with the connected tools:
Start a crawl of https://quotes.toscrape.com/ with maxPages=2
and maxDepth=1. Retrieve Markdown and links. Keep the returned
crawl ID and query that existing task until it reaches a terminal
state. Retrieve its page results and read every available Markdown
reference. Report discovered URLs, completed pages, failed pages,
and whether the available records cover my requested scope.
Do not resubmit the crawl while checking its progress.
The official Crawl MCP repository documents the distinction between starting a crawl, checking its status, retrieving page results, and reading referenced artifacts.
Step 3: Validate coverage before exporting
A bounded two-page request in this walkthrough completed with one returned page. This demonstrates that maxPages is an upper limit, not a promised output count. Investigate discovery scope before claiming catalog completeness.
Result pagination also differs from source pagination. A cursor used to retrieve another batch of completed Crawl results belongs to the result API; it does not necessarily represent the target website's next product page. Export only validated page artifacts, then apply your record schema.
Why do paginated scrapers miss records or get stuck?
Paginated scrapers commonly fail because navigation state, record identity, and completion criteria are treated as the same thing.
Symptom
Likely cause
Practical response
Same records appear on every page
Repeated response or ignored page argument
Compare fingerprints; stop and inspect the source
Records vanish after a restart
Checkpoint advanced before storage
Commit records and checkpoint in one transaction
Job ends unusually early
Missing selector mistaken for terminal state
Validate the page and expected end evidence
Duplicate variants inflate totals
URL identity differs from business identity
Normalize against the source's item/variant model
Cursor fails halfway through
Expired token or changed query
Apply documented recovery; preserve diagnostics
Cost grows without useful records
Retries or rendering without progress
Cap attempts and measure accepted records per job
For transient failures, use bounded retries and respect source-provided retry guidance. Do not apply unlimited retries to validation failures or access denials. The production scraper error-handling guide explains how to classify these outcomes before retrying.
Measure cost per accepted unique record, not simply requests sent. Include rendered-page work, artifact storage, retries, and review effort. A partially completed job with a clear checkpoint can be more useful than a cheap job whose completeness is unknown.
What should you verify before scheduling a recurring crawl?
Verify restart behavior, termination, deduplication, and scope against a small known dataset before scheduling recurring collection.
Keep an expected range or sample where possible. Alert when page counts fall sharply, required-field completeness changes, or the same fingerprint appears repeatedly. Retain enough source evidence to diagnose a broken selector without automatically re-downloading the whole site.
Begin with a bounded run, review the resulting records, and increase the budget only when the collection contract is stable.
No. HTML next links and documented API continuations can often be collected with an HTTP client. Use a browser when the required authorized interaction or rendering makes it necessary.
Q: Can I stop when a response contains no records?
Only if the source defines that response as the end. Validate the response type and continuation fields before treating an empty batch as completion.
Q: Is record deduplication enough to prevent loops?
No. Deduplication can hide an infinite navigation loop by keeping storage counts unchanged. Track page fingerprints, continuation tokens, and a finite request budget separately.
Q: Can a crawl limit prove that I collected the whole site?
No. A limit bounds work. Completeness requires evidence about the expected scope, discovered pages, failed pages, and inaccessible or interaction-dependent content.
Q: Should a retry start the job from the beginning?
Usually it should resume from the last committed checkpoint. Restart only when the source's continuation contract requires it, and preserve stable record keys to manage overlap.
Lena Zhou
Nov. 27th 2026
Experience Nstproxy Crawl - Start Your Free Trial Today
Crawl entire websites with a single API request
Turn any website into Markdown, HTML, JSON, links, PDFs and more — without managing crawling infrastructure.