One page of search results is rarely enough. A research tool or an enrichment pipeline needs sustained coverage of a topic, which means fetching page after page. Search API pagination brings two problems with it. The same page can come back twice under slightly different URLs, and a pagination token that has gone bad doesn't always fail loudly.
This tutorial builds a paginator that returns unique, normalized results and remembers where each one came from. It stops under limits you set, carries pagination tokens without touching them, and notices when a search quietly starts over. Search API pagination and deduplication are the two halves of one job, so it handles them together.
Install the package and put your Spidra key in the environment as SPIDRA_API_KEY:
# pip install spidra
import argparse
import base64
import hashlib
import json
import os
import re
import sys
import time
from collections import Counter
from dataclasses import asdict, dataclass, field
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit
from spidra import (
Spidra,
SpidraAuthenticationError,
SpidraError,
SpidraJobFailedError,
SpidraPaymentRequiredError,
SpidraRateLimitError,
SpidraServerError,
SpidraTimeoutError,
SpidraValidationError,
)
What a real second page looks like
Search returns one opaque token for each source that has more results. You pass it back to get the next page. Here are a first page and the start of the second, using the real response:
# needs SPIDRA_API_KEY
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
query = "python web scraping tutorial"
first = client.search(query, sources=["web"], limit=5)
for r in first.data.web:
print(r.position, r.title, "|", r.url)
token = first.data.next_page_tokens
second = client.search(query, sources=["web"], limit=5, page_tokens=token)
seen = {r.url for r in first.data.web}
new = [r for r in second.data.web if r.url not in seen]
print(f"page 2: {len(second.data.web)} results, {len(new)} new")
for r in new[:3]:
print(r.position, r.title, "|", r.url)
Output:
1 Python Web Scraping Tutorial - GeeksforGeeks | https://www.geeksforgeeks.org/python/python-web-scraping-tutorial/
2 A Practical Introduction to Web Scraping in Python | https://realpython.com/python-web-scraping-practical-introduction/
3 Python Web Scraping Tutorial - Online Tutorials Library | https://www.tutorialspoint.com/python_web_scraping/index.htm
4 Python Web Scraping Tutorials | https://realpython.com/tutorials/web-scraping/
5 Python Web Scraping Tutorial: Complete Guide (2025) | https://generalistprogrammer.com/tutorials/python-web-scraping-tutorial-complete-guide
page 2: 5 results, 5 new
6 Python Web Scraping (Learning Path) - Real Python | https://realpython.com/learning-paths/python-web-scraping/
7 Beautiful Soup: Build a Web Scraper With Python | https://realpython.com/beautiful-soup-web-scraper-python/
8 Python Web Scraping: Step-By-Step Tutorial - ScraperAPI | https://www.scraperapi.com/web-scraping/python/
This code runs one search, takes its token, and uses the token to fetch the next five results. Notice that position keeps counting: page two starts at 6, so a position is a place in the whole result list, not in the page.
Page two was five new results here, but a URL from page one can occasionally reappear, which is why the code checks. Results change over time, so what you see will differ.
Three behaviors shape everything below. Pass the token back unchanged. A changed or expired token isn't an error, and that source simply runs as a fresh search. And every extra page is charged like a new search, so a limit is also a budget.
Tokens, not offsets
Search APIs page in two styles. Offset pagination takes a number: Google's Custom Search API uses start, and it never returns more than 100 results for a query, however many documents match. Cursor pagination takes a token, which is how Spidra and YouTube's Data API work. The token identifies the next page, and you can't build one yourself.
That has consequences. Keep the token exactly as received, because editing it can turn it into a request for page one. Keep it beside the query that produced it, and keep the query, the limit and the filters identical on every page.
And don't mix styles: Spidra also takes a plain page number, but with it position restarts at 1, so positions from the two styles can't be compared. Use tokens.
A search to practice on
To run everything offline, this stand-in for client.search follows the documented rules. Tokens are sealed, positions keep counting, and a token that is unknown or too old starts a fresh search:
def seal(start, calls):
"""A token that means nothing outside this fake, like the real ones."""
return "v1." + base64.urlsafe_b64encode(f"{calls}:{start}".encode()).decode()
def start_of(issued, token, calls, expire_after):
"""Where a token points. A token that is unknown or too old points back at the start."""
known = issued.get(token)
if not known or (expire_after is not None and calls - known["call"] > expire_after):
return 0
return known["start"]
class FakeSearch:
def __init__(self, results, expire_after=None):
self.results, self.expire_after, self.calls, self.issued = results, expire_after, 0, {}
def search(self, query, sources, limit, page_tokens=None, **filters):
self.calls += 1
start = start_of(self.issued, (page_tokens or {}).get("web"), self.calls, self.expire_after)
rows = self.results[start : start + limit]
items = [SimpleNamespace(position=start + n + 1, **row) for n, row in enumerate(rows)]
more = start + limit < len(self.results)
token = seal(start + limit, self.calls) if more else None
self.issued[token] = {"start": start + limit, "call": self.calls}
tokens = {"web": token} if more else None
return SimpleNamespace(data=SimpleNamespace(web=items, next_page_tokens=tokens))
The results are made up, with three duplicates seeded in the way real ones arrive: a tracking parameter and a fragment, a capitalized host with an explicit port, and a www host with a trailing slash:
def make_results(count):
rows = [(f"Guide {n}", f"https://site{n}.test/guide") for n in range(1, count + 1)]
results = [{"title": title, "url": url} for title, url in rows]
results[4]["url"] = "https://site1.test/guide/../guide?utm_source=mail#top"
results[8]["url"] = "HTTPS://Site3.TEST:443/guide"
results[9]["url"] = "http://www.site4.test/guide/"
return results
fake = FakeSearch(make_results(12))
page = fake.search("guides", ["web"], 5)
for item in page.data.web:
print(item.position, item.url)
print("next token:", page.data.next_page_tokens)
Output:
1 https://site1.test/guide
2 https://site2.test/guide
3 https://site3.test/guide
4 https://site4.test/guide
5 https://site1.test/guide/../guide?utm_source=mail#top
next token: {'web': 'v1.MTo1'}
The first call returns five results and a token. Result 5 is already the same page as result 1, so even a single page can repeat itself. The token means nothing outside the fake, which is the point: your code has to treat real tokens the same way.
Normalize to compare, not to fetch
Two URLs for one page need one key. Established libraries such as w3lib and url-normalize fix case, default ports, percent-encoding and dot segments.
Neither removes tracking parameters, www, trailing slashes or index.html, because those can change what a server returns, so a search deduplicator has to decide on its own. w3lib's documentation also warns that its canonical form may point to a different resource than the original, so you should request the original.
That's the rule here. Normalize to get a key for comparing results, and keep the URL as the search returned it. The safe rules always apply. The aggressive rules are opt-in:
Rule | Safe | Aggressive |
|---|---|---|
Lowercase scheme and host, ASCII host name, default port dropped | Yes | Yes |
Dot segments, percent-encoding case, fragment | Yes | Yes |
Tracking parameters removed, remaining parameters sorted | Yes | Yes |
| No | Yes |
| No | Yes |
Trailing slash and | No | Yes |
Blank parameters ignored | No | Yes |
TRACKING = re.compile(r"^(utm_.+|gclid|fbclid|msclkid|srsltid|mc_cid|mc_eid|igshid)$", re.I)
UNRESERVED = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
DEFAULT_PORTS = {"http": 80, "https": 443}
INDEX = re.compile(r"/index\.(html?|php)$", re.I)
PATH_SAFE = "/%:@!$&'()*+,;=~-._"
def clean_escapes(text):
"""%7e becomes ~ and %2f stays %2F: decode only characters that never need escaping."""
def fix(match):
char = chr(int(match.group(1), 16))
return char if char in UNRESERVED else "%" + match.group(1).upper()
return re.sub(r"%([0-9a-fA-F]{2})", fix, text)
def remove_dots(path):
"""Resolve . and .. segments the way a browser would."""
out = []
for part in path.split("/")[1:]:
if part == "..":
out and out.pop()
elif part != ".":
out.append(part)
return "/" + "/".join(out + [""] * path.endswith(("/.", "/..")))
HOST_OK = re.compile(r"[a-z0-9._-]+|[0-9a-f:.]+")
def host_key(host):
"""Lowercase, no trailing dot, and international names in their ASCII form."""
try:
ascii_host = host.rstrip(".").lower().encode("idna").decode("ascii")
except UnicodeError as error:
raise ValueError(f"not a valid host name: {host!r}") from error
if not HOST_OK.fullmatch(ascii_host):
raise ValueError(f"not a valid host name: {host!r}")
return ascii_host
def clean_query(query, aggressive):
"""Drop tracking parameters and sort the rest, so parameter order never makes a duplicate."""
pairs = [(k, v) for k, v in parse_qsl(query, keep_blank_values=True) if not TRACKING.match(k)]
pairs = [(k, v) for k, v in pairs if v or not aggressive]
return urlencode(sorted(pairs), quote_via=quote, safe="")
def netloc_for(parts, host, aggressive):
"""The host, with the port kept only when it isn't the default for the original scheme."""
if aggressive:
host = host.removeprefix("www.")
host = f"[{host}]" if ":" in host else host
port = parts.port
return host if port in (None, DEFAULT_PORTS[parts.scheme.lower()]) else f"{host}:{port}"
def split_web_url(url, aggressive):
"""(parts, netloc) for an http or https address. Anything else is refused."""
parts = urlsplit(url.strip())
if parts.scheme.lower() not in DEFAULT_PORTS or not parts.hostname:
raise ValueError(f"not a web address: {url!r}")
try:
return parts, netloc_for(parts, host_key(parts.hostname), aggressive)
except ValueError as error:
raise ValueError(f"not a web address: {url!r}") from error
def clean_path(path, aggressive):
path = remove_dots(clean_escapes(quote(path or "/", safe=PATH_SAFE)))
return (INDEX.sub("/", path).rstrip("/") or "/") if aggressive else path
def normalize_url(url, aggressive=False):
"""A key for comparing results. The default rules are safe. aggressive=True also merges
http and https, drops www and trailing slashes, and ignores index files and blank parameters."""
parts, netloc = split_web_url(url, aggressive)
scheme = "https" if aggressive else parts.scheme.lower()
query = clean_query(parts.query, aggressive)
return urlunsplit((scheme, netloc, clean_path(parts.path, aggressive), query, ""))
def result_id(key):
"""A short id that depends only on the key, so the same page gets the same id every run."""
return hashlib.sha1(key.encode("utf-8")).hexdigest()[:12]
urls = ["HTTPS://Site3.TEST:443/guide", "https://example.com/a%2fb"]
urls += ["https://site1.test/guide/../guide?utm_source=mail#top"]
urls += ["https://example.com/%7Euser", "https://example.com/p?q=a b&utm_medium=x&id=7"]
for url in urls:
print(url, "->", normalize_url(url))
Output:
HTTPS://Site3.TEST:443/guide -> https://site3.test/guide
https://example.com/a%2fb -> https://example.com/a%2Fb
https://site1.test/guide/../guide?utm_source=mail#top -> https://site1.test/guide
https://example.com/%7Euser -> https://example.com/~user
https://example.com/p?q=a b&utm_medium=x&id=7 -> https://example.com/p?id=7&q=a%20b
This code turns each URL into its comparison key. The host loses its case and its default port, the tracking parameter and the fragment disappear, %7E becomes ~, and %2F stays escaped, because a slash inside a path segment isn't the same page as a slash between segments.
The aggressive rules merge variants that most sites treat as one page, but not all do. Here's the difference on the www and http duplicate:
url = "http://www.site4.test/guide/"
other = "https://site4.test/guide"
print("safe: ", normalize_url(url))
print("aggressive:", normalize_url(url, aggressive=True))
print("merged with the https page:", normalize_url(url, True) == normalize_url(other, True))
Output:
safe: http://www.site4.test/guide/
aggressive: https://site4.test/guide
merged with the https page: True
Safe mode keeps http, www and the trailing slash, so it treats this as a different page. Aggressive mode merges it with the plain https address. Start with safe, and move to aggressive only if you've checked that the sites you collect from serve the same page either way.
Remember where each result came from
A unique result still needs a history. Each record keeps its first page and position, plus every sighting with the URL exactly as returned. Its id comes from the key alone, so the same page has the same id on every run:
def sighting(item, page):
return {"page": page, "position": item.position, "url": item.url}
def new_record(key, item, page):
"""The first time a page is seen. Its identity is the key, so its id never changes."""
return {
"id": result_id(key),
"key": key,
"url": item.url,
"title": item.title,
"first_seen": {"page": page, "position": item.position},
"sightings": [sighting(item, page)],
}
def add_sighting(record, item, page):
record["sightings"].append(sighting(item, page))
return record
This code builds the record that the paginator stores for each unique result. A duplicate adds a sighting and leaves the record's first sighting alone.
The paginator
Failures need a message and an exit code, so a script that calls this one can tell a missing key from an exhausted account:
NO_API_KEY = 3 # missing or rejected
UNKNOWN = 1
NO_RESULTS = 10 # the first page was empty
BAD_QUERY = 11 # there was nothing to search for
TOKEN_RESTART = 12 # a page token was ignored and the search started over
class Failure(Exception):
def __init__(self, message, code):
super().__init__(message)
self.message, self.code = message, code
RULES = [
(
SpidraAuthenticationError,
NO_API_KEY,
"the Spidra API key was rejected. Check SPIDRA_API_KEY.",
),
(SpidraPaymentRequiredError, 4, "the account is out of credits, or its payment is overdue."),
(SpidraRateLimitError, 5, "too many requests. Wait a moment, or raise --pause."),
(SpidraTimeoutError, 6, "the search took too long."),
(SpidraJobFailedError, 7, None), # its own message says what failed
(SpidraValidationError, 8, "the request was rejected as invalid."),
(SpidraServerError, 9, "Spidra had a problem on its side. Try again."),
]
def explain(error):
"""The first rule that matches wins. List the specific errors before the general one."""
for kind, code, text in RULES:
if isinstance(error, kind):
return Failure(text or str(error), code)
return Failure(str(error), UNKNOWN)
This code maps each Spidra exception to one exit code and one plain message.
The search itself is frozen. A Query holds everything that must stay the same on every page, and fetch_page sends the tokens back exactly as they came:
@dataclass(frozen=True)
class Query:
"""Everything that must stay the same on every page. Frozen, so it can't drift."""
text: str
source: str = "web"
limit: int = 10
filters: dict = field(default_factory=dict)
class PageError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.message, self.code = message, code
def fetch_page(client, query, tokens):
"""One search call. The tokens go back exactly as they came, never rebuilt or edited."""
extra = {"page_tokens": tokens} if tokens else {}
try:
result = client.search(
query.text, sources=[query.source], limit=query.limit, **query.filters, **extra
)
except SpidraError as error:
failure = explain(error)
raise PageError(failure.message, failure.code) from error
return getattr(result.data, query.source) or [], result.data.next_page_tokens
def restarted(items, last_position):
"""With tokens, positions keep counting. If they start over, the token was ignored."""
first = next((i.position for i in items if i.position), None)
return bool(last_position) and first is not None and first <= last_position
restarted is the check for a token that was silently ignored. With real tokens, positions keep counting, so if a page starts at or below the last position you saw, the search has started over.
A run keeps its own state, and a Limits object holds the limits the run stops at. There's no way to turn them off, and a limit below 1 is refused:
@dataclass
class Run:
records: dict = field(default_factory=dict)
seen: set = field(default_factory=set) # keys from earlier sessions, when resuming
counts: Counter = field(default_factory=Counter) # fetched, raw, duplicates, skipped, dropped
page: int = 0 # pages seen so far, counting earlier sessions
stale: int = 0 # pages in a row with nothing new
tokens: dict = None
last_position: int = 0
stop: str = ""
error: str = ""
code: int = 0
def run_stats(run):
names = ("fetched", "raw", "duplicates", "skipped", "dropped")
return {
"unique": len(run.records),
**{n: run.counts[n] for n in names},
"stop": run.stop,
"error": run.error,
}
def run_cursor(run, query):
"""Enough to continue later. The tokens are saved exactly as they were received."""
seen = sorted(run.seen | set(run.records))
return {
"query": asdict(query),
"tokens": run.tokens,
"last_position": run.last_position,
"page": run.page,
"seen": seen,
}
@dataclass(frozen=True)
class Limits:
"""The limits a run stops at. They are explicit, and there is no way to switch them off."""
max_pages: int = 5
max_results: int = 50
patience: int = 1 # pages with nothing new that are allowed before stopping
pause: float = 0.0 # seconds between pages
def __post_init__(self):
if min(self.max_pages, self.max_results, self.patience) < 1:
raise ValueError("max_pages, max_results and patience must be at least 1")
This code defines what a run remembers, and the limits it stops at. run_cursor is everything needed to continue later, with the tokens saved exactly as received.
Merging a page is four small functions. add decides whether a result is new, a duplicate, or over the limit. stop_reason says why to stop, in a fixed order:
def key_of(item, aggressive):
try:
return normalize_url(item.url, aggressive)
except (ValueError, AttributeError, TypeError):
return None
def add(run, key, item, limits):
"""Add one result. Returns True when it was new."""
if key in run.records or key in run.seen:
run.counts["duplicates"] += 1
key in run.records and add_sighting(run.records[key], item, run.page)
elif len(run.records) >= limits.max_results:
run.counts["dropped"] += 1
else:
run.records[key] = new_record(key, item, run.page)
return True
return False
def absorb(run, items, limits, aggressive):
"""Merge one page into the run. Returns how many results were new."""
keys = [key_of(item, aggressive) for item in items]
run.counts["skipped"] += keys.count(None)
return sum(add(run, key, item, limits) for key, item in zip(keys, items) if key is not None)
def stop_reason(run, new, limits, source):
"""Why to stop after this page, or an empty string to keep going."""
run.stale = 0 if new else run.stale + 1
if len(run.records) >= limits.max_results:
return "max_results"
if not (run.tokens or {}).get(source):
return "no_more_pages"
if run.stale >= limits.patience:
return "no_new_results"
return "max_pages" if run.counts["fetched"] >= limits.max_pages else ""
The class below ties them together. Add its methods in order:
class Paginator:
def __init__(self, client, query, limits=None, aggressive=False, sleep=time.sleep):
self.client, self.query, self.limits = client, query, limits or Limits()
self.aggressive, self.sleep = aggressive, sleep
def record_page(self, run, items, tokens):
run.page, run.tokens = run.page + 1, tokens
run.counts.update(fetched=1, raw=len(items))
run.last_position = max([i.position or 0 for i in items] + [run.last_position])
new = absorb(run, items, self.limits, self.aggressive)
run.stop = stop_reason(run, new, self.limits, self.query.source)
def step(self, run):
"""Fetch and merge one page. Sets run.stop when the run should end."""
try:
items, tokens = fetch_page(self.client, self.query, run.tokens)
except PageError as error:
run.stop, run.error, run.code = "error", error.message, error.code
return
if restarted(items, run.last_position):
run.stop = "token_restart"
else:
self.record_page(run, items, tokens)
def collect(self, cursor=None):
run = self.resume(cursor) if cursor else Run()
while not run.stop:
self.step(run)
run.stop or self.sleep(self.limits.pause)
return run
def resume(self, cursor):
if cursor["query"] != asdict(self.query):
raise ValueError("this cursor belongs to a different search")
return Run(
seen=set(cursor["seen"]),
page=cursor["page"],
tokens=cursor["tokens"],
last_position=cursor["last_position"],
)
step fetches one page and ends the run on an error or a restart. collect repeats it until something says stop, and resume continues from a saved cursor, refusing a cursor from a different search.
Now run it on the made-up results:
paginator = Paginator(FakeSearch(make_results(12)), Query("guides", limit=5))
run = paginator.collect()
print(run_stats(run))
Output:
{'unique': 10, 'fetched': 3, 'raw': 12, 'duplicates': 2, 'skipped': 0, 'dropped': 0, 'stop': 'no_more_pages', 'error': ''}
Twelve raw results became ten unique ones, over three pages, and the run stopped because there were no more pages. Two duplicates were merged. The third seeded duplicate, the www and http one, stays separate in safe mode. Here's what a record that was seen twice remembers:
key = "https://site1.test/guide"
record = run.records[key]
print(json.dumps(record, indent=2))
Output:
{
"id": "b7acd6095a3b",
"key": "https://site1.test/guide",
"url": "https://site1.test/guide",
"title": "Guide 1",
"first_seen": {
"page": 1,
"position": 1
},
"sightings": [
{
"page": 1,
"position": 1,
"url": "https://site1.test/guide"
},
{
"page": 1,
"position": 5,
"url": "https://site1.test/guide/../guide?utm_source=mail#top"
}
]
}
The record kept the first URL the search returned, and a sighting for each time the page appeared. Here both are on page one, at positions 1 and 5. The second sighting shows the messy address the duplicate arrived under, so you can always see what the search really returned.
Stop under limits you set
Pagination without a limit is a loop that spends money. Each limit stops the run for its own reason, and the reason is recorded:
for limits in (Limits(max_pages=1), Limits(max_pages=2), Limits(max_results=7), Limits()):
run = Paginator(FakeSearch(make_results(12)), Query("guides", limit=5), limits).collect()
print(limits.max_pages, limits.max_results, "->", run.stop, len(run.records))
Output:
1 50 -> max_pages 4
2 50 -> max_pages 8
5 7 -> max_results 7
5 50 -> no_more_pages 10
This code runs the same search four times with different limits. The page limit stops at one or two pages, the result limit stops exactly at seven results, and with the defaults the run stops only when the results run out. A result limit never overshoots: extra results are counted, not kept.
A bad token restarts the search quietly
This is the failure that needs care. A token that has expired, or that has been altered, doesn't raise an error. The search starts over, so your "page two" is page one again. Without a check you'd collect the first page twice and think you were going deeper. Here, the fake's tokens expire right away, which is the worst case:
client = FakeSearch(make_results(12), expire_after=0)
run = Paginator(client, Query("guides", limit=5)).collect()
print(run.stop, "| kept:", len(run.records), "| pages merged:", run.counts["fetched"])
print("error:", repr(run.error))
Output:
token_restart | kept: 4 | pages merged: 1
error: ''
The paginator asked for page two, saw positions start again at 1, and stopped with the reason token_restart. It kept the four unique results it already had, since one of the first five was a duplicate, and didn't merge the restarted page.
It's a stop, not an exception, so nothing already collected is lost. The documentation says a changed or expired token runs as a fresh search, and positions restarting is how you'd see it.
Continue later
A search can be too deep for one sitting. The cursor holds the query, the tokens, the last position and the keys already seen:
client, query = FakeSearch(make_results(12)), Query("guides", limit=5)
first = Paginator(client, query, Limits(max_pages=1)).collect()
cursor = run_cursor(first, query)
print(json.dumps(cursor["tokens"]), cursor["page"], cursor["last_position"], len(cursor["seen"]))
second = Paginator(client, query).collect(cursor)
print(run_stats(second))
Output:
{"web": "v1.MTo1"} 1 5 4
{'unique': 6, 'fetched': 2, 'raw': 7, 'duplicates': 1, 'skipped': 0, 'dropped': 0, 'stop': 'no_more_pages', 'error': ''}
The first run fetched one page and saved a cursor with the token exactly as received. The second run continued from it. It numbered its pages from 2, caught one result it had already seen in the first run, and ran to the end. Tokens don't last forever, so a cursor from last week may hit the restart check, which is what the check is for.
Cost and depth
Each page is charged like a new search, and search submissions are limited to 60 per minute, so the command waits a second between pages by default. A search returns a bounded window of results, not the whole web. Google's own API stops at 100.
How deep Spidra goes depends on the query, and it isn't guaranteed. The paginator stops when the token runs out, and it reports why. For more coverage, vary the query and add filters, such as included domains, and don't expect one query to go on forever.
The finished command
The command wraps the paginator. It writes one JSON line per unique result, saves a cursor when more pages may exist, and exits with a code your scheduler can read:
def check_query(text):
if not text or not text.strip():
raise Failure("give a topic to search for.", BAD_QUERY)
return text.strip()
def write_jsonl(path, records, append=False):
with open(path, "a" if append else "w", encoding="utf-8") as handle:
handle.writelines(json.dumps(record, ensure_ascii=False) + "\n" for record in records)
def save_state(path, cursor):
"""Write to a temporary file, then rename it, so a crash never leaves half a cursor."""
path = Path(path)
temporary = path.with_name(path.name + ".tmp")
temporary.write_text(json.dumps(cursor, indent=2), encoding="utf-8")
os.replace(temporary, path)
def exit_code(run):
if run.stop == "error":
return run.code
if run.stop == "token_restart":
return TOKEN_RESTART
return NO_RESULTS if not run.records and not run.seen else 0
def summary(run):
s = run_stats(run)
lines = [
f"Collected {s['unique']} unique results from {s['fetched']} pages (stopped: {s['stop']})"
]
lines.append(f"{s['raw']} raw results | {s['duplicates']} duplicates | {s['skipped']} skipped")
lines[-1] += f" | {s['dropped']} over the limit"
return lines + ([f"Error: {s['error']}"] if s["error"] else [])
def build_parser():
ask = argparse.ArgumentParser(description="Collect unique search results across pages.")
ask.add_argument("query")
ask.add_argument("--source", default="web", choices=["web", "news", "research", "developer"])
ask.add_argument("--limit", type=int, default=10, help="results per page, 1 to 20")
ask.add_argument("--max-pages", type=int, default=3, help="pages to fetch in this run")
ask.add_argument("--max-results", type=int, default=50, help="unique results to keep")
ask.add_argument("--pause", type=float, default=1.0, help="seconds between pages")
ask.add_argument(
"--aggressive", action="store_true", help="also merge http/https, www, trailing slashes"
)
ask.add_argument("--out", default="results.jsonl")
ask.add_argument("--state", help="a JSON file that remembers where this search stopped")
ask.add_argument("--resume", action="store_true", help="continue from --state")
return ask
def make_client():
if not os.environ.get("SPIDRA_API_KEY"):
raise Failure("set SPIDRA_API_KEY to your Spidra key first.", NO_API_KEY)
return Spidra(api_key=os.environ["SPIDRA_API_KEY"], api_url=os.environ.get("SPIDRA_API_URL"))
def run_search(args, client, sleep):
query = Query(check_query(args.query), args.source, args.limit)
limits = Limits(args.max_pages, args.max_results, pause=args.pause)
cursor = json.loads(Path(args.state).read_text(encoding="utf-8")) if args.resume else None
run = Paginator(client, query, limits, args.aggressive, sleep).collect(cursor)
write_jsonl(args.out, run.records.values(), append=args.resume)
if args.state and run.tokens and run.stop not in ("token_restart", "no_more_pages"):
save_state(args.state, run_cursor(run, query))
return run
def main(argv=None, client=None, sleep=time.sleep):
args = build_parser().parse_args(argv)
try:
if args.resume and not (args.state and Path(args.state).exists()):
raise Failure("--resume needs a --state file from an earlier run.", BAD_QUERY)
run = run_search(args, client or make_client(), sleep)
except Failure as failure:
print(f"error: {failure.message}", file=sys.stderr)
return failure.code
except (ValueError, OSError) as error:
print(f"error: {error}", file=sys.stderr)
return 1
print("\n".join(summary(run)))
return exit_code(run)
Save the pieces as paginate_search.py and run python paginate_search.py "python web scraping tutorial" --max-pages 3 --state state.json. It prints how many unique results it collected and why it stopped, and writes results.jsonl. Run it again with --resume to continue from the saved cursor, and add --aggressive to merge http, www and trailing-slash variants.
The exit code says what happened: 0 for success, 3 for the key, 4 for credits or an overdue payment, 5 for the rate limit, 10 when the first page was empty, 11 for a blank query, and 12 when a token was ignored and the search started over. Partial results are always written first.
What this doesn't do
It compares addresses, not content, so two different URLs with the same text stay separate. Mirrors and syndicated copies need a content check on top. It follows one source at a time, and tokens are kept per source, so a multi-source search needs one paginator for each.
How long a token lasts isn't documented, so the paginator checks instead of assuming. And a page limit is not a promise of coverage: measure how many unique results you got per query before you build on it.
Sustained coverage, on a budget
You now have a paginator that returns unique results with a history, never edits a token, stops where you told it to, and catches the quiet failure that costs most. That's what a research tool or an enrichment product needs underneath it.
Here is what Spidra adds when coverage has to be sustained:
- One Search API across several sources. Web, news, images, videos, research papers and developer results, each with its own token, so you can page through any of them the same way.
- Filters you can rely on. Domain filters are enforced before results come back, which keeps a deep search on the sites you care about.
- Positions that keep counting. A token continues the result list, so provenance means something across pages.
- Typed errors. A rate limit, an empty account and a bad request each raise their own exception, so the paginator can keep what it has and report a clear reason.
- A direct path to the content. Hand the unique URLs to Scrape, or to a batch of up to 50 URLs, and the search becomes enriched records, not a list of links.
A single page of results answers a question. Sustained coverage of a topic is a different job, and the part that goes wrong is rarely the first page. Spidra can't promise unlimited depth, and the paginator won't pretend it can. What it gives you is a search you can page through, measure and stop.
Create a free account, run paginate_search.py on a query you care about, and look at the duplicate count. Our post on searching for PDF documents uses the same pagination for documents, and the batch scrape docs show how to turn unique URLs into content. For how Spidra's search compares with other search APIs, see our comparison of web search APIs.