Skip to main content
TutorialsNovember 26, 2026 · 10 min read

How to search for PDF files with Python and an API

Find PDF files with Spidra Search and Python. Verify document links, export titles and source domains, and parse selected reports.

How to search for PDF files with Python and an API

You need PDF reports for a research project, but you don't know where the files are hosted. A regular web search might return articles discussing those reports, company websites, or investor-relations pages instead of the actual documents.

For a document-ingestion pipeline, you need something more useful: PDF URLs, document titles, and source domains that you can verify before processing.

This tutorial shows how to search for PDF files using Python and Spidra Search. We'll collect annual reports from renewable energy companies, check the returned links, export the results to JSON, and optionally pass selected PDFs to Spidra Parse.

We'll also cover what happens when a PDF search returns no results.

Search for PDF files using Spidra

Let's collect 2025 annual reports from companies operating in the renewable energy industry.

Our search query is:

annual report 2025 renewable energy

A regular search could return webpages, company news, and links to the actual reports.

Spidra Search supports a filetype filter, so we can ask specifically for PDF documents.

Install the Python SDK:

pip install spidra

Create a Spidra API key and save it as the SPIDRA_API_KEY environment variable.

Now run the search:

import os
from spidra import Spidra

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,
)

The two settings to pay attention to are sources=["web"] and filetype="pdf".

The first tells Spidra to search the web. The second restricts the results to PDF files.

The filter applies to web Search, not Spidra's separate research-paper search source.

Search returns structured results with titles, URLs, descriptions, and positions. It doesn't require you to know the document URLs beforehand.

The Spidra Search documentation covers additional filters, including domain restrictions and pagination.

What a PDF search returns

For our query, a completed Spidra Search execution returned five results.

Position

Search result title

Source domain

1

PDF Annual Report 2025

europeanenergy.com

2

PDF RWE_Annual Report_2025

www.rwe.com

3

PDF Annual Report 2025 - cdn.orsted.com

cdn.orsted.com

4

PDF ANNUAL REPORT 2025 - metisenergy.com

metisenergy.com

5

PDF BEP 2025 Annual Report

bep.brookfield.com

These titles and URLs come from an earlier completed Spidra Search response. They aren't fabricated examples, but a new search may return different results.

All five were returned under the PDF filetype filter.

During a separate inspection, the Ørsted, Metis Energy, RWE, and Brookfield links were opened as readable PDFs. The European Energy URL was also returned by Search, but its full contents weren't inspected during that check.

A filetype-filtered Search result is a candidate document. Before ingesting it, your application should still check whether the URL currently serves a valid PDF.

Export PDF URLs, titles, and source domains

Let's turn the Search response into a document inventory.

For each result, we'll save its title, original URL, source domain, and search position.

Python's urllib.parse module can extract the hostname from a URL.

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

records = []

for result in results.data.web or []:
    records.append({
        "position": result.position,
        "title": result.title,
        "url": result.url,
        "source_domain": urlsplit(
            result.url
        ).hostname,
        "requested_filetype": "pdf",
    })

Path("pdf_candidates.json").write_text(
    json.dumps(records, indent=2),
    encoding="utf-8",
)

The script saves the results to pdf_candidates.json.

For example, the record constructed from the Ørsted search result looks like this:

{
  "position": 3,
  "title": "PDF Annual Report 2025 - cdn.orsted.com",
  "url": "https://cdn.orsted.com/-/media/annual-2025/annual-report-2025.pdf",
  "source_domain": "cdn.orsted.com",
  "requested_filetype": "pdf"
}

The URL and title come from the completed Search response. The other fields are added by our Python code.

Notice that source_domain is the hostname in the returned URL. It isn't necessarily the company's main website domain.

Keeping the original hostname matters when documents are hosted on CDNs or separate document servers.

This inventory is already useful for research databases, document catalogs, and applications that need to track where a report was discovered.

But requested_filetype only tells us which filter was used. It doesn't prove that the file is currently accessible.

Verify that the URLs contain actual PDFs

A URL ending in .pdf doesn't guarantee that the response contains a PDF document.

The file might have moved, require authentication, or redirect to an error page.

A verification step should examine the actual response, rather than trusting the filename.

Two useful checks are the HTTP content type and the file signature.

PDF files normally begin with:

%PDF-

For the companion project, we created a probe_pdf() function that requests the beginning of each file and checks for this signature.

It also records the final URL after redirects and the content type reported by the server.

You can use it like this:

# probe_pdf() is defined in the companion find_pdfs.py
from find_pdfs import probe_pdf

for record in records:
    check = probe_pdf(record["url"])

    record["verified_pdf"] = check["verified_pdf"]
    record["verification_status"] = check["status"]

    record["verified_url"] = (
        check["final_url"]
        if check["verified_pdf"]
        else None
    )

The verifier distinguishes a confirmed PDF from a failed request, an unsafe URL, or a response that doesn't contain PDF content.

It doesn't assume a document is invalid simply because the server blocks an automated request.

That distinction matters when ingesting research documents from different organizations. Some servers reject range requests or automated clients even when the file opens normally in a browser.

The companion implementation checks HTTPS URLs and redirects, but it isn't a complete security boundary for untrusted internet URLs. Production services should also enforce network-level protections against private-address access, DNS changes, unsafe redirects, and excessive downloads.

Once verified, the records can retain both their original Search URLs and their final document URLs.

Handle PDF searches that return no results

Not every PDF search returns documents.

This is especially important when you're searching for a specific publication, reporting year, or research paper.

Earlier Spidra PDF searches returned no results for:

annual report 2026

and:

attention is all you need transformer paper

Those were empty results from those particular requests. They don't mean the documents don't exist, and the same queries may produce results in a later search.

The broader query:

annual report 2025 renewable energy

returned the five reports shown earlier.

A topical search such as:

climate change report

also returned PDF links in a separate completed Search example.

The lesson is to adjust search specificity without losing the original research intent.

If a narrow query returns nothing, you can try removing an unnecessary qualifier or using the document's broader topic.

Your code should also distinguish an empty result from an API failure.

web_results = results.data.web or []

if not web_results:
    print("No PDF documents found.")

For an empty result set, this produces:

No PDF documents found.

A successful request with no matches isn't the same as a request that failed.

For repeatable research workflows, save the query alongside the result set. That makes it easier to review which searches found documents and which ones need different wording.

Read two of the discovered PDF reports

Finding the files solves the discovery problem. The next question is whether they contain the information your application needs.

Let's look at two documents returned by the search.

Ørsted Annual Report 2025

The Ørsted Annual Report 2025 contains information about the company's operations, management, sustainability, and financial performance.

The independently inspected PDF includes this text:

Our Management Report consists of the Management’s Review and the Sustainability Statements.

That gives us a useful indication of the document's contents.

Metis Energy Annual Report 2025

The Metis Energy Annual Report 2025 covers its renewable energy operations and financial reporting.

The document describes the company as a:

developer, owner and operator of renewable energy assets across the Asia Pacific region.

These excerpts come from inspecting the original PDF documents, not from a Spidra Parse response.

To build a reproducible ingestion pipeline, the next step is to process the selected files through Parse and retain the actual returned Markdown.

Pass selected PDFs to Spidra Parse

If you only need titles and PDF links, the discovery workflow can stop here.

But a research application may also need document text for indexing, searching, summarization, or extraction into structured fields.

Spidra Parse accepts PDF URLs and returns Markdown. You can choose specific pages instead of processing an entire report.

Let's use the two reports from the previous section.

First, define the URLs:

pdf_urls = [
    "https://cdn.orsted.com/-/media/annual-2025/annual-report-2025.pdf",
    "https://metisenergy.com/wp-content/uploads/METIS_ENERGY_AR2025.pdf",
]

Before parsing a document, you can request an estimate.

estimate = client.estimate_parse(
    pdf_urls[0],
    pages="1-2",
)

The estimate reports information such as the document's page count and the credits needed to process the selected pages.

It also returns a reusable file ID.

Parse the selected pages:

doc = client.parse(
    file_id=estimate.file_id,
    pages="1-2",
    include_pages=True,
)

This retrieves Markdown for the requested pages. With include_pages=True, the response also includes page-level information.

You can apply the same workflow to both reports and save their Markdown files:

from pathlib import Path

for index, url in enumerate(pdf_urls, start=1):
    estimate = client.estimate_parse(
        url,
        pages="1-2",
    )

    doc = client.parse(
        file_id=estimate.file_id,
        pages="1-2",
        include_pages=True,
    )

    if not doc.markdown:
        raise RuntimeError(
            f"No Markdown returned for {url}"
        )

    Path(f"report_{index}.md").write_text(
        doc.markdown,
        encoding="utf-8",
    )

This code uses documented SDK methods, but the two report-specific Parse requests haven't been run in the available evidence. Their exact returned Markdown therefore isn't shown as completed API output.

Once you run them, compare the Markdown with the original pages. Check whether headings, tables, and relevant fields were preserved correctly.

Parse also supports prompts and JSON Schema when your application needs specific fields rather than full text.

For that next step, see our guide to scraping PDFs and extracting structured JSON.

Run the complete PDF discovery workflow

The companion Python project combines Search, PDF verification, and export into one script.

Install the dependencies:

pip install spidra requests

With SPIDRA_API_KEY configured, run:

python find_pdfs.py \
  --query "annual report 2025 renewable energy" \
  --limit 5

The script searches for PDF documents, verifies returned URLs, and writes the results to:

pdf_search_results/
├── pdf_results.json
└── pdf_results.csv

The JSON and CSV files retain the result titles, original URLs, source domains, and verification outcomes.

You can optionally process the first page of up to two verified documents:

python find_pdfs.py \
  --query "annual report 2025 renewable energy" \
  --parse-top 2

This option selects the first two successfully verified results in search order. It doesn't specifically target Ørsted and Metis Energy. Use the explicit URLs from the previous section if those are the reports you need.

If you want to inspect the earlier Search result without making a new API request, use replay mode:

python find_pdfs.py --replay

The preserved result produces:

Query: annual report 2025 renewable energy
Search results: 5
Link verification: skipped (historical replay)
Saved: pdf_search_results/pdf_results.json

Replay mode uses the saved Search response. It doesn't check whether the links are still accessible or submit any Parse jobs.

A live run performs the verification checks and, when requested, saves the Markdown returned by Parse.

When to use Search and when to use Parse

You don't need to parse every PDF you discover.

The right workflow depends on what your application needs.

Goal

Recommended workflow

Discover PDF reports on a topic

Search with filetype="pdf"

Build a catalog of downloadable reports

Search, verify URLs, export metadata

Read a known PDF

Parse the document URL

Extract selected pages

Parse with a page range

Collect structured fields

Parse with a prompt and JSON Schema

Process many selected documents

Verify the documents, then use a document-processing workflow

If you already know the exact document URL, skip Search.

If your application only needs document metadata, don't process the PDF content unnecessarily.

And if you need information from scanned pages, remember that the underlying document may not have a selectable text layer. Parse can read scanned PDF pages, but the extracted content should still be checked against the original document.

Build a PDF discovery pipeline you can reuse

You can start a document-ingestion workflow with a research topic instead of a list of known URLs.

Spidra Search finds candidate PDF documents. Your application verifies that those URLs currently serve PDFs and exports their titles, links, and source domains.

When you need the contents, Spidra Parse can process the selected documents into Markdown or structured fields.

Keeping these steps separate makes it easier to review sources and avoid processing documents that aren't relevant to the task.

Create a Spidra account and run a PDF-only Search for reports related to your project. Verify the results before passing selected documents into Parse.

Frequently asked questions

Use a web search API that supports filetype filtering. With Spidra Search, set sources=["web"] and filetype="pdf" to request PDF documents. The response includes titles, URLs, descriptions, and search positions.

Share this article

You build the product.
Spidra handles the data work.

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