Skip to main content
TutorialsNovember 27, 2026 · 19 min read

How to search specifically for PDF documents

Search the web for PDF files only with a filetype filter, verify each link, and parse the ones you pick. Includes what to do when a query returns nothing.

How to search specifically for PDF documents

A normal web search for a report returns web pages: landing pages, press releases, summaries of the report. You wanted the report itself. Searching for PDF files with an API means asking for documents only, then checking that what comes back really is one, because search results aren't always what their titles say.

This tutorial builds a script that takes a research topic and returns PDF URLs, the domains they came from and clean titles. It checks every link, and it can hand the ones you choose to a parser. It also says what to do when a search finds nothing, which narrow searches often do.

Install the packages and put your Spidra key in the environment as SPIDRA_API_KEY:

# pip install spidra requests
import argparse
import csv
import hashlib
import ipaddress
import json
import os
import re
import sys
import threading
import time
from datetime import date
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit

import requests
from spidra import (
    Spidra,
    SpidraAuthenticationError,
    SpidraError,
    SpidraJobFailedError,
    SpidraPaymentRequiredError,
    SpidraRateLimitError,
    SpidraServerError,
    SpidraTimeoutError,
    SpidraValidationError,
)

Search for PDFs, not pages

Search takes a filetype option. The only value it accepts is "pdf", and it restricts web results to PDF files. Here's a topic query, with the exact call and what it returned:

# needs SPIDRA_API_KEY
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
query = "annual report 2025 renewable energy"
results = client.search(query, sources=["web"], filetype="pdf", limit=5)
for r in results.data.web:
    print(r.title, "|", r.url)

Output:

PDF Annual Report 2025 | https://europeanenergy.com/wp-content/uploads/2026/02/annual-report-2025.pdf
PDF RWE_Annual Report_2025 | https://www.rwe.com/-/media/RWE/documents/05-investor-relations/finanzkalendar-und-veroeffentlichungen/2025-GJ/RWE_Annual-Report_2025.pdf
PDF Annual Report 2025 - cdn.orsted.com | https://cdn.orsted.com/-/media/annual-2025/annual-report-2025.pdf
PDF ANNUAL REPORT 2025 - metisenergy.com | https://metisenergy.com/wp-content/uploads/METIS_ENERGY_AR2025.pdf
PDF BEP 2025 Annual Report | https://bep.brookfield.com/sites/brookfield-bep-v2/files/Brookfield-BEP-IR-V2/annual-reports/bep-2025-annual-report.pdf

Five reports from five companies, and every address is a PDF. Each result has a title, a url, a description and a position. limit runs from 1 to 20 per page, and a result page carries a token for the next one. A PDF search isn't instant, so give it time.

Google's own Custom Search API has a file-type filter too. It needs a Programmable Search Engine ID, returns at most 10 results per page and never more than 100 for a query. With Spidra, you pass one option.

Clean the results

The titles need work. Each starts with PDF, and some end with the site's domain. The addresses can carry tracking parameters, and the same report can appear twice. Here are the five results above as data, so the cleanup runs offline:

PAIRS = [
    ("PDF Annual Report 2025",
     "https://europeanenergy.com/wp-content/uploads/2026/02/annual-report-2025.pdf"),
    ("PDF RWE_Annual Report_2025",
     "https://www.rwe.com/-/media/RWE/documents/05-investor-relations/"
     "finanzkalendar-und-veroeffentlichungen/2025-GJ/RWE_Annual-Report_2025.pdf"),
]
PAIRS += [
    ("PDF Annual Report 2025 - cdn.orsted.com",
     "https://cdn.orsted.com/-/media/annual-2025/annual-report-2025.pdf"),
    ("PDF ANNUAL REPORT 2025 - metisenergy.com",
     "https://metisenergy.com/wp-content/uploads/METIS_ENERGY_AR2025.pdf"),
    ("PDF BEP 2025 Annual Report",
     "https://bep.brookfield.com/sites/brookfield-bep-v2/files/Brookfield-BEP-IR-V2/"
     "annual-reports/bep-2025-annual-report.pdf"),
]
ITEMS = [SimpleNamespace(title=title, url=url) for title, url in PAIRS]

The address helpers come first. They drop tracking parameters and fragments, so one document has one address, and they find the domain:

TRACKING = re.compile(r"^(utm_.+|gclid|fbclid|srsltid|mc_cid|mc_eid)$", re.I)


def normalize_url(url):
    """The same document at the same address: no fragment, no tracking parameters."""
    parts = urlsplit(url.strip())
    pairs = [
        (k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if not TRACKING.match(k)
    ]
    return urlunsplit(
        (parts.scheme.lower(), parts.netloc.lower(), parts.path, urlencode(pairs), "")
    )
def source_domain(url):
    return (urlsplit(url).hostname or "").removeprefix("www.")


def same_site(host, domain):
    host = host.lower().removeprefix("www.")
    return bool(domain) and (
        host == domain or domain.endswith("." + host) or host.endswith("." + domain)
    )


def file_stem(url):
    """The file's own name, for when a result has no usable title."""
    name = unquote(urlsplit(url).path.rsplit("/", 1)[-1])
    return re.sub(r"\.pdf$", "", name, flags=re.I).replace("_", " ").replace("-", " ").strip()

The title cleaner removes the PDF prefix, and a trailing - domain only when that domain is the result's own. Sustainability Report 2025 - UBS keeps its UBS, because that's part of the title. If nothing is left, it falls back to the file's name:

PDF_PREFIX = re.compile(r"^\s*\[?PDF\]?(?=[\s:\-\]]|$)[\s:\-\]]*", re.I)
TAIL = re.compile(r"\s[-|\u2013\u2014]\s*([\w-]+(?:\.[\w-]+)+)\s*$")


def clean_title(title, url=""):
    """Search titles for PDFs start with 'PDF' and often end with ' - domain'. Both are noise."""
    text, domain = PDF_PREFIX.sub("", title or "").strip(), source_domain(url)
    tail = TAIL.search(text)
    if tail and same_site(tail.group(1), domain):
        text = text[: tail.start()].strip()
    return text or file_stem(url)
def dedupe(items):
    """Keep the first result for each address. Results are in the order the search gave them."""
    seen, kept = set(), []
    for item in items:
        key = normalize_url(item.url)
        if key not in seen:
            seen.add(key)
            kept.append(item)
    return kept
def to_rows(items):
    return [
        {
            "rank": rank,
            "title": clean_title(item.title, item.url),
            "domain": source_domain(item.url),
            "url": normalize_url(item.url),
        }
        for rank, item in enumerate(items, start=1)
    ]
rows = to_rows(dedupe(ITEMS))
for row in rows:
    print(row["rank"], row["domain"], "|", row["title"])

Output:

1 europeanenergy.com | Annual Report 2025
2 rwe.com | RWE_Annual Report_2025
3 cdn.orsted.com | Annual Report 2025
4 metisenergy.com | ANNUAL REPORT 2025
5 bep.brookfield.com | BEP 2025 Annual Report

Search for the topic, and follow the pages

Failures need a message and an exit code, so a script that calls this one can tell a missing key from an empty search:

NO_API_KEY = 3  # missing or rejected
UNKNOWN = 1
NO_RESULTS = 10  # the search worked and found no PDFs
BAD_QUERY = 11  # there was nothing to search for


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 and run it again."),
    (SpidraTimeoutError, 6, "the search took too long. PDF searches can be slow, so try again."),
    (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)

Now the search itself. A blank query is refused before it costs a request, and each result page's token is passed to the next:

def check_query(query):
    """Spidra needs words to search for. Say so before spending a request."""
    if not query or not query.strip():
        raise Failure(
            "give a topic to search for, such as 'renewable energy annual report 2025'.", BAD_QUERY
        )
    return query.strip()
def one_page(client, query, limit, tokens):
    extra = {"page_tokens": tokens} if tokens else {}
    try:
        return client.search(
            check_query(query), sources=["web"], filetype="pdf", limit=limit, **extra
        )
    except SpidraError as error:
        raise explain(error) from error
def search_pdfs(client, query, limit=10, pages=1):
    """PDF-only web results, in order, across up to `pages` result pages."""
    items, tokens = [], None
    for _ in range(pages):
        result = one_page(client, query, limit, tokens)
        items += result.data.web or []
        tokens = result.data.next_page_tokens
        if not tokens or not tokens.get("web"):
            break
    return items

Empty results are normal

A narrow PDF search can return nothing, and that's not a bug. A year with the words "annual report" and no topic can come back empty. So can a paper's exact title. PDF search works best on topics, such as renewable energy annual report. An empty search costs nothing, so broaden it and try again. The script says so in one line and exits with its own code:

def empty_message(query):
    return (
        f"no PDFs found for {query!r}. PDF search works best on topics: try dropping the year "
        "or the quotes, and use the words a report would use. Nothing was charged."
    )
query = "annual report 2026"
print(empty_message(query))
print("exit code:", NO_RESULTS)

Output:

no PDFs found for 'annual report 2026'. PDF search works best on topics: try dropping the year or the quotes, and use the words a report would use. Nothing was charged.
exit code: 10

And a blank query, which never reaches Spidra:

try:
    check_query("   ")
except Failure as failure:
    print(failure.code, "|", failure.message)

Output:

11 | give a topic to search for, such as 'renewable energy annual report 2025'.

When a search is empty, drop the year, drop the quotes, and use the words the document itself would use. Don't assume a topic has no PDFs because one phrasing found none.

Verify before you rely on a link

A result is a claim that a URL is a PDF. Check it twice: once from your side, and once with Spidra. First, you're about to fetch addresses a search engine gave you. Refuse the ones that point at your own machine or network, including the tricks that spell 127.0.0.1 as one large number:

NUMERIC_HOST = re.compile(r"(0x[0-9a-f]+|[0-9]+)(\.(0x[0-9a-f]+|[0-9]+))*")


def is_internal(host):
    """localhost, or an address on your own machine or network, even when written as 0x7f000001."""
    if host == "localhost" or host.endswith(".localhost"):
        return True
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        return bool(NUMERIC_HOST.fullmatch(host))
    return address.is_private or address.is_loopback or address.is_link_local or address.is_reserved
def safe_to_fetch(url, allow_private=False):
    """http or https only, and not an address that points back at your own machine or network."""
    parts = urlsplit(url)
    host = (parts.hostname or "").lower()
    if parts.scheme not in ("http", "https") or not host:
        return False
    return allow_private or not is_internal(host)
urls = ["https://example.com/r.pdf", "http://127.0.0.1/r.pdf", "http://2130706433/r.pdf"]
urls.append("file:///etc/passwd")
for url in urls:
    print(safe_to_fetch(url), url)

Output:

True https://example.com/r.pdf
False http://127.0.0.1/r.pdf
False http://2130706433/r.pdf
False file:///etc/passwd

This blocks addresses written as IPs. A hostname that resolves to a private address isn't caught, so for stricter needs, resolve the name and check the result, or fetch through a proxy.

Then read the first bytes. A real PDF starts with %PDF-, whatever the server labels it. Some sites serve a real PDF as application/octet-stream, and some answer a missing file with a friendly HTML page and a 200 status. The first bytes settle both:

MAGIC = b"%PDF-"
HEADERS = {"Range": "bytes=0-7", "User-Agent": "pdf-finder/1.0"}


def total_size(response):
    """The full size: Content-Range if the server honored the range, else Content-Length."""
    span = response.headers.get("Content-Range", "")
    length = span.rsplit("/", 1)[-1] if "/" in span else response.headers.get("Content-Length", "")
    return int(length) if length.isdigit() else None


def blocked(status):
    if status in (401, 403):
        return "access denied (a login or a bot check)"
    return "not found" if status in (404, 410) else f"the server answered {status}"
def failed(url, reason):
    return {
        "ok": False,
        "reason": reason,
        "content_type": "",
        "size": None,
        "status": None,
        "final_url": url,
    }
def first_bytes(url, timeout):
    """(what the server said, the file's first 8 bytes). Reads only the start of the file."""
    with requests.get(url, headers=HEADERS, stream=True, timeout=timeout) as response:
        start = next(response.iter_content(8), b"") if response.status_code < 400 else b""
        said = {
            "status": response.status_code,
            "content_type": response.headers.get("Content-Type", ""),
        }
        return {**said, "size": total_size(response), "final_url": response.url}, start
def check_pdf(url, timeout=15, allow_private=False):
    """Read the first bytes. A real PDF starts with %PDF-, whatever its Content-Type says."""
    if not safe_to_fetch(url, allow_private):
        return failed(url, "not fetched: not a public web address")
    try:
        said, start = first_bytes(url, timeout)
    except requests.RequestException as error:
        return failed(url, f"could not fetch it ({type(error).__name__})")
    reason = (
        blocked(said["status"])
        if said["status"] >= 400
        else "" if start.startswith(MAGIC) else "not a PDF"
    )
    return {**said, "ok": not reason, "reason": reason}

To run it offline, a tiny local site serves documents the way real sites do, good and bad:

def respond(handler, status, kind, body, headers):
    time.sleep(float(headers.get("delay", 0)))
    handler.send_response(status)
    for name, value in {"Content-Type": kind, "Content-Length": str(len(body)), **headers}.items():
        name != "delay" and handler.send_header(name, value)
    handler.end_headers()
    handler.wfile.write(body)
class Site(BaseHTTPRequestHandler):
    routes = {}
    log_message = lambda *args: None

    def do_GET(self):
        route = self.routes.get(self.path, (404, "text/html", b"Not found", {}))
        respond(self, *route)


class Quiet(ThreadingHTTPServer):
    """A client that only wanted a file's first bytes hangs up. That isn't worth printing."""

    def handle_error(self, request, client_address):
        pass
def serve(routes, port=8841):
    """{path: (status, content type, body, extra headers)} -> the site's base URL."""
    handler = type("Handler", (Site,), {"routes": routes})
    server = Quiet(("127.0.0.1", port), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return f"http://127.0.0.1:{port}"
PDF = b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n"
routes = {
    "/report.pdf": (200, "application/pdf", PDF, {}),
    "/export.pdf": (200, "application/octet-stream", PDF, {}),
    "/moved.pdf": (200, "text/html", b"<html>Page not found</html>", {}),
    "/old.pdf": (302, "text/html", b"", {"Location": "/report.pdf"}),
    "/private.pdf": (403, "text/html", b"denied", {}),
}
base = serve(routes)
for path in ("/report.pdf", "/export.pdf", "/moved.pdf", "/old.pdf", "/private.pdf", "/gone.pdf"):
    result = check_pdf(base + path, allow_private=True)
    print(f"{path:13s} ok={result['ok']!s:5} {result['content_type']:26s} {result['reason']}")

Output:

/report.pdf   ok=True  application/pdf            
/export.pdf   ok=True  application/octet-stream   
/moved.pdf    ok=False text/html                  not a PDF
/old.pdf      ok=True  application/pdf            
/private.pdf  ok=False text/html                  access denied (a login or a bot check)
/gone.pdf     ok=False text/html                  not found

The octet-stream file passes, because its bytes say it's a PDF. The "page not found" with a 200 status fails, because they don't. The redirect is followed, and the 403 and the missing file say why they failed.

The second check is Spidra's own, and it's free. An estimate says whether Spidra can read the document and how many pages it has, without parsing or charging anything:

def estimate(client, url):
    """Spidra's free estimate: is it a document it can read, and how many pages?"""
    try:
        found = client.estimate_parse(url)
    except SpidraError as error:
        return {"ok": False, "reason": str(error), "pages": None, "file_name": ""}
    if found.format.upper() != "PDF":
        return {
            "ok": False,
            "reason": f"format is {found.format}",
            "pages": None,
            "file_name": found.file_name,
        }
    return {"ok": True, "reason": "", "pages": found.total_pages, "file_name": found.file_name}
# needs SPIDRA_API_KEY
estimate = client.estimate_parse(rows[0]["url"])
print(estimate.file_name, estimate.format, estimate.total_pages, "pages")

Output:

annual-report-2025.pdf PDF 181 pages

Now you know what you're about to parse. A 181-page report is a very different job from a 4-page notice, which is why the next step takes a page limit.

Parse the ones you choose

Parse turns a PDF into Markdown. Give it the link, and cap the pages while you're deciding whether a document is worth it. Here's what the first pages of a well-known paper look like:

# needs SPIDRA_API_KEY
doc = client.parse("https://arxiv.org/pdf/1706.03762", max_pages=3)
print(doc.status, doc.total_pages, "pages in the PDF")
for line in doc.markdown.splitlines()[:7]:
    print(line)

Output:

completed 15 pages in the PDF
### Provided proper attribution is provided, Google hereby grants permission to

reproduce the tables and figures in this paper solely for use in journalistic or scholarly works.

## Attention Is All You Need

#### Ashish Vaswani

And a second paper, one page only:

# needs SPIDRA_API_KEY
doc = client.parse("https://arxiv.org/pdf/2506.06962v3", max_pages=1)
print(doc.status, doc.total_pages, "pages in the PDF")
print(doc.markdown.splitlines()[0])

Output:

completed 18 pages in the PDF
## AR-RAG: Autoregressive Retrieval Augmentation for Image Generation

The first call returned three pages of a 15-page paper, and the second one page of an 18-page paper. Parse reads each page's own text and uses AI only for scanned pages, so a text PDF is quick and a scan still works. Our post on scanned versus text PDFs covers how the two differ.

This function parses one chosen PDF into a Markdown file that remembers its source. A document that fails is reported, not raised, so one bad file doesn't stop a batch:

def slug_for(url, limit=50):
    """A readable file name that stays unique: host and path, plus a short hash of the URL."""
    parts = urlsplit(url)
    words = re.sub(r"[^a-z0-9]+", "-", f"{parts.hostname}{parts.path}".lower()).strip("-")
    return f"{words[-limit:].strip('-')}-{hashlib.sha1(url.encode('utf-8')).hexdigest()[:8]}"


def front_matter(url, title, pages, today):
    """YAML with the source first. json.dumps gives strings that are safely quoted."""
    return (
        f"---\nsource_url: {json.dumps(url)}\ntitle: {json.dumps(title, ensure_ascii=False)}\n"
        f"pages_parsed: {pages[0]}\ntotal_pages: {pages[1]}\nfetched_on: {today}\n---\n\n"
    )
def parse_to_markdown(client, row, out_dir, max_pages=2, today=None):
    """Parse the first pages of one PDF. A document that fails is reported, never raised."""
    try:
        doc = client.parse(row["url"], max_pages=max_pages)
    except SpidraError as error:
        return {"url": row["url"], "path": None, "error": str(error)}
    path = Path(out_dir) / f"{slug_for(row['url'])}.md"
    path.parent.mkdir(parents=True, exist_ok=True)
    head = front_matter(
        row["url"], row["title"], (doc.pages_parsed, doc.total_pages), today or date.today()
    )
    temporary = path.with_name(path.name + ".tmp")
    temporary.write_text(head + (doc.markdown or ""), encoding="utf-8")
    os.replace(temporary, path)
    return {"url": row["url"], "path": str(path), "error": None, "pages": doc.pages_parsed}
url = "https://a.test/r.pdf"
head = front_matter(url, "Annual Report 2025", (2, 181), "2026-11-27")
print(head)

Output:

---
source_url: "https://a.test/r.pdf"
title: "Annual Report 2025"
pages_parsed: 2
total_pages: 181
fetched_on: 2026-11-27
---

Two cautions before you keep what you parse. Documents can include personal details, such as authors' email addresses on a paper's first page, so trim them before you publish anything. And a PDF being public doesn't make it free to copy or re-host: check its license.

Make it repeatable

Run the same search next week and most of the PDFs will be the ones you've already handled. A small ledger of addresses means only the new ones are parsed. It writes to a temporary file and renames it, so a crash never leaves half a ledger:

def load_seen(path):
    path = Path(path)
    if not path.exists():
        return set()
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except ValueError as error:
        raise ValueError(f"{path} is not a valid list of URLs ({error})") from error
    if not isinstance(data, list) or not all(isinstance(url, str) for url in data):
        raise ValueError(f"{path} is not a valid list of URLs (expected a JSON list of strings)")
    return set(data)
def save_seen(path, seen):
    """Write to a temporary file, then rename it, so a crash never leaves half a ledger."""
    path = Path(path)
    temporary = path.with_name(path.name + ".tmp")
    temporary.write_text(json.dumps(sorted(seen), indent=2), encoding="utf-8")
    os.replace(temporary, path)


def new_only(rows, seen):
    return [row for row in rows if normalize_url(row["url"]) not in seen]
rows = [{"url": "https://a.test/x.pdf?utm_source=mail"}, {"url": "https://b.test/y.pdf"}]
seen = {"https://a.test/x.pdf"}
print([row["url"] for row in new_only(rows, seen)])
save_seen("seen.json", seen | {"https://b.test/y.pdf"})
print(sorted(load_seen("seen.json")))

Output:

['https://b.test/y.pdf']
['https://a.test/x.pdf', 'https://b.test/y.pdf']

The tracking parameter doesn't make the first PDF look new, because both sides are normalized. A PDF that fails to parse isn't added, so the next run tries it again. For many PDFs at once, see how to batch process PDFs in Python.

The finished script

The pieces come together in find_pdfs.py. verify_row runs both checks, find searches and raises the empty-search failure, and parse_new parses only the verified PDFs the ledger hasn't seen:

SKIPPED = {"ok": False, "reason": "", "pages": None}


def verify_row(row, client, allow_private=False):
    """Two free checks: the file starts like a PDF, and Spidra can read it."""
    fetched = check_pdf(row["url"], allow_private=allow_private)
    read = estimate(client, row["url"]) if fetched["ok"] else SKIPPED
    ok = fetched["ok"] and read["ok"]
    note = "" if ok else fetched["reason"] or read["reason"]
    return {**row, "verified": ok, "pages": read["pages"], "note": note}
def find(client, query, limit, pages, verify, allow_private=False):
    items = dedupe(search_pdfs(client, query, limit, pages))
    if not items:
        raise Failure(empty_message(query), NO_RESULTS)
    rows = to_rows(items)
    return [verify_row(row, client, allow_private) for row in rows] if verify else rows


def show(rows):
    for row in rows:
        status = row.get("note") or (f"{row['pages']} pages" if row.get("pages") else "")
        print(f"{row['rank']:>2}  {row['domain']:<28} {row['title'][:48]:<48} {status}")
def write_csv(path, rows):
    with open(path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
def parse_new(client, rows, args, seen):
    """Parse the first few verified PDFs this ledger hasn't seen, and remember them."""
    pick = [r for r in new_only(rows, seen) if r.get("verified", True)][: args.parse]
    for row in pick:
        done = parse_to_markdown(client, row, args.outdir, args.max_pages)
        print(
            f"parsed {done['path']}"
            if done["path"]
            else f"could not parse {row['url']}: {done['error']}"
        )
        seen.add(normalize_url(row["url"])) if done["path"] else None
    return seen
def build_parser():
    ask = argparse.ArgumentParser(
        description="Find PDFs for a topic, check them, parse the ones you pick."
    )
    ask.add_argument("query")
    ask.add_argument("--limit", type=int, default=10, help="results per page, 1 to 20")
    ask.add_argument("--pages", type=int, default=1, help="result pages to read")
    ask.add_argument("--verify", action="store_true", help="check each link is a PDF")
    ask.add_argument("--parse", type=int, default=0, help="parse the first N new, verified PDFs")
    ask.add_argument("--max-pages", type=int, default=2, help="pages to parse from each")
    ask.add_argument("--seen", help="a JSON file of PDFs already handled")
    ask.add_argument("--out", default="pdfs.csv")
    ask.add_argument("--outdir", default="pdf-markdown")
    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(args, client, allow_private=False):
    seen = load_seen(args.seen) if args.seen else set()  # a bad ledger fails before any search
    rows = find(client, args.query, args.limit, args.pages, args.verify, allow_private)
    show(rows)
    write_csv(args.out, rows)
    if args.parse:
        seen = parse_new(client, rows, args, seen)
        args.seen and save_seen(args.seen, seen)
def main(argv=None, client=None, allow_private=False):
    args = build_parser().parse_args(argv)
    try:
        run(args, client or make_client(), allow_private)
    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
    return 0

Save the pieces as find_pdfs.py and run it with python find_pdfs.py "annual report 2025 renewable energy" --verify --parse 2 --seen seen.json. It prints a row for each PDF, with its domain, cleaned title and page count, and writes pdfs.csv. The ledger is read first, so a damaged ledger stops the run before any search is spent.

Failures are one error: line with their own exit code: 3 for the Spidra key, 4 for credits or an overdue payment, 10 for a search that found no PDFs, and 11 for a blank query.

What this doesn't do

The file-type option accepts only pdf, so Word and Excel files need a different route. Search finds PDFs. It doesn't list every PDF on a site, and results aren't sorted by date. If you need every document on one known site, map or crawl that site instead.

Narrow searches may find nothing, and a good result today may be gone next month, which is what the verify step is for. Verification can't tell you the document is the right one, so read the title and the first page before you rely on it.

From a search to a document pipeline

You now have a script that finds PDFs for a topic, throws away the links that aren't documents, parses the ones you pick, and remembers what it's done. That last part is what makes it repeatable.

Here is what Spidra gives you for the whole path:

  • One option restricts a search to PDFs. An empty search costs nothing, so you can broaden it freely.
  • A free estimate before you spend anything. You see the format and the page count, and you decide.
  • Parse reads text PDFs from their own text and uses AI only on scanned pages. So the same call handles a clean report and a scan.
  • You parse what you need. Page ranges, a page cap, per-page output, and a file ID that lets you parse the same file again for 24 hours without sending it twice. A single document can run to 2,000 pages.
  • Fields, not just text. Send a schema and get a paper's title and authors back as data, ready for a database.
  • Many documents at once. Batch parse takes a list of PDFs and gives each its own result, and the same call reads Word, Excel and PowerPoint files too.

If you already have the URLs, skip the search. If you need only one known report, download it.

But when the job is to keep finding and processing documents on a topic, such as reports, white papers and public datasets, a search that returns only PDFs, a free check and a parser behind one key is far less to maintain than three separate tools.

Create a free account, run find_pdfs.py on a topic from your own field, and then schedule it to run weekly with a ledger. If your documents are forms or tables, our guide to scraping PDFs into structured JSON shows the next step.

Frequently asked questions

Use a search API that has a file-type filter. With Spidra Search, add the PDF file-type option to a web search, and it returns PDF links with their titles. Then check each link before you rely on it, and parse the ones you choose.

Share this article

You build the product.
Spidra handles the data work.

Start with 300 free credits, about 300 pages. No credit card required.