Skip to main content
November 26, 2026 · 14 min read

How to find and extract research papers with Python

Search research papers with Python, read their PDFs into page-level Markdown, and save source-linked records, with failures and gaps in plain view.

How to find and extract research papers with Python

To search research papers with Python and keep their text, you need two things: a way to find papers, and a way to read their PDFs. This tutorial builds collect.py. It searches the research source in Spidra Search, chooses a small set of papers, reads their PDFs into page-level Markdown with Parse, and saves one source-linked record per paper. It's a small, reproducible sample, and it makes no claim about how much of the literature any source covers.

Search the research source

Search has a research source that covers arXiv, PubMed, bioRxiv and medRxiv. Each result has a title, a link, a short description and a position, plus a date, a source name, an authors string and a DOI when the source has them. Install the SDK with pip install spidra (Python 3.9 or later) and put your key in SPIDRA_API_KEY. The topic is "retrieval augmented generation evaluation":

# explore.py
import os
from datetime import datetime, timezone

from spidra import Spidra

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
QUERY = "retrieval augmented generation evaluation"
NOW = datetime.now(timezone.utc).isoformat(timespec="seconds")
found = client.search(QUERY, sources=["research"], limit=10)
for r in found.data.research:
    print(r.position, r.source, r.date, "|", r.title)

Output:

[NEED: output of the search block, ten research results with position, source, date and title]

Results aren't sorted by date, and one query can return papers from more than one source. Paging through further results works the way it does for any search, and How to use a web search API with Python covers it.

Turn each result into a paper without filling gaps

The tempting cleanup is a default: the search snippet as the abstract, a guessed author list, a year from the title. This Paper keeps what the API returned and leaves everything else None:

# papers.py
import html
import re
from dataclasses import asdict, dataclass
from typing import Optional
from urllib.parse import urlsplit

from spidra import SpidraJobFailedError, SpidraValidationError


@dataclass(frozen=True)
class Paper:
    title: Optional[str]
    url: str                          # the link the search returned
    source: Optional[str] = None      # arXiv, PubMed, bioRxiv or medRxiv
    date: Optional[str] = None        # ISO text, exactly as returned
    authors: Optional[str] = None     # one string, as returned
    doi: Optional[str] = None
    abstract: Optional[str] = None    # the search description: a snippet, not the full abstract
    position: int = 0
    query: str = ""
    retrieved_at: str = ""

to_paper() builds the record. A result without a link is dropped, because there is nothing to open or de-duplicate on:

def clean(value):
    """Decode HTML entities and trim. A missing or blank field becomes None, never a stand-in."""
    if value is None:
        return None
    text = html.unescape(value).strip()
    return text or None


def to_paper(item, query, retrieved_at):
    url = (item.url or "").strip()
    if not url:
        return None
    return Paper(title=clean(item.title), url=url, source=clean(item.source), date=clean(item.date),
                 authors=clean(item.authors), doi=clean(item.doi), abstract=clean(item.description),
                 position=item.position, query=query, retrieved_at=retrieved_at)

Here is one real research result, a PubMed paper, as the API returns it, run through to_paper():

# one_result.py
from spidra.types import SearchResultItem

from papers import citation, pdf_url, to_paper

raw = {
    "title": "BioVDB: biological vector database for high-throughput gene expression meta-analysis.",
    "url": "https://doi.org/10.3389/frai.2024.1366273",
    "description": "High-throughput sequencing has created an exponential increase in the amount of gene expression data ...",
    "date": "2024-03-08",
    "source": "PubMed",
    "authors": "Winnicki MJ, Brown CA, Porter HL, Giles CB, Wren JD.",
    "doi": "10.3389/frai.2024.1366273",
    "position": 1,
}
paper = to_paper(SearchResultItem(**raw), "example query", "2026-11-25T12:00:00+00:00")
print(paper.source, "|", paper.date, "|", paper.authors)
print(pdf_url(paper))
print(citation(paper))

Output:

PubMed | 2024-03-08 | Winnicki MJ, Brown CA, Porter HL, Giles CB, Wren JD.
(None, 'doi.org link is a landing page, not a PDF')
Winnicki MJ, Brown CA, Porter HL, Giles CB, Wren JD. (2024) BioVDB: biological vector database for high-throughput gene expression meta-analysis. PubMed https://doi.org/10.3389/frai.2024.1366273

Two details matter later. authors is one string, not a list, so don't split it unless you have to. And the link is a DOI link, which leads to a landing page and not to the paper's PDF.

Measure what came back

Before you choose anything, count what the sample actually has. coverage() reports, for each source, how many papers came back with a date, authors, a DOI and a usable PDF link:

def coverage(papers):
    """For each source: how many papers, and how many came back with a date, authors, a DOI and a PDF link."""
    rows = {}
    for p in papers:
        row = rows.setdefault(p.source or "unknown", {"papers": 0, "date": 0, "authors": 0, "doi": 0, "pdf": 0})
        row["papers"] += 1
        row["date"] += p.date is not None
        row["authors"] += p.authors is not None
        row["doi"] += p.doi is not None
        row["pdf"] += pdf_url(p)[0] is not None
    return rows
from papers import coverage, to_paper

papers = [p for p in (to_paper(r, QUERY, NOW) for r in found.data.research) if p]
for source, row in coverage(papers).items():
    print(source.ljust(8), row)

Output:

[NEED: output of the coverage block for the ten results]

These counts describe this query on this day. They say nothing about how well a source covers its field, so don't generalize from them.

Choose papers, and say why you skipped the rest

A small collection needs rules you can state. select() removes repeats (the same DOI, or the same normalized title), optionally drops papers older than a date, and keeps the first few. Every skipped paper comes back with its reason:

def paper_key(paper):
    if paper.doi:
        return "doi:" + paper.doi.lower()
    return "title:" + re.sub(r"[^a-z0-9]+", " ", (paper.title or "").lower()).strip()


def select(papers, since=None, keep=8):
    """Split papers into (chosen, skipped). Every skipped paper carries its reason."""
    seen, chosen, skipped = set(), [], []
    for p in papers:
        key = paper_key(p)
        if not p.title:
            skipped.append((p.url, "no title"))
        elif key in seen:
            skipped.append((p.title, "same paper as an earlier result"))
        elif since and p.date and p.date < since:
            skipped.append((p.title, f"published before {since}"))
        else:
            seen.add(key)
            chosen.append(p)
    skipped += [(p.title, f"beyond the first {keep}") for p in chosen[keep:]]
    return chosen[:keep], skipped

Find each paper's PDF, and don't guess

Search returns a link to a paper, and that link isn't always a PDF. arXiv has a predictable PDF address, so pdf_url() derives it from the paper's link and says so. For every other source it uses the link only when the link already is a PDF, and otherwise returns None with a reason. A paper with no PDF link is a result you report, not an error to hide:

def pdf_url(paper):
    """Returns (url or None, note). Only links the search result supports; nothing is guessed."""
    parts = urlsplit(paper.url)
    if parts.netloc.endswith("arxiv.org"):
        match = re.match(r"/(abs|pdf)/(.+?)(?:\.pdf)?$", parts.path)
        if match:
            how = "derived from the arXiv link" if match.group(1) == "abs" else "the link is already a PDF"
            return f"https://arxiv.org/pdf/{match.group(2)}", how
    if parts.path.lower().endswith(".pdf"):
        return paper.url, "the link is already a PDF"
    return None, f"{parts.netloc} link is a landing page, not a PDF"

The PubMed result above shows the second case: (None, 'doi.org link is a landing page, not a PDF').

Check the cost, then parse

Parse reads a PDF into Markdown, page by page, at 1 credit per page. It uses each page's own text and calls AI only for scanned pages. An estimate is free and tells you the page count and the credits before anything is spent, and the file can then be parsed by its file_id without fetching it again. read_pdf() does both and caps the pages. A document that can't be parsed, such as a password-protected PDF or a link that can't be fetched, comes back as a failure with a reason and costs nothing, so the function returns it instead of raising:

def read_pdf(client, url, max_pages=12):
    """Estimate for free, then parse by file id. Returns (estimate, job, None) or (estimate, None, reason)."""
    estimate = None
    try:
        estimate = client.estimate_parse(url, max_pages=max_pages)
        job = client.parse(file_id=estimate.file_id, max_pages=max_pages, include_pages=True)
    except (SpidraJobFailedError, SpidraValidationError) as error:
        return estimate, None, str(error)
    return estimate, job, None

Only those two errors are caught. A rate limit or an empty credit balance stops the run on purpose, so it doesn't turn into a list of "failed" papers. Here is the real first page of an arXiv paper, read with a one-page cap:

# read_one.py  (client as before)
import json

from papers import Paper, build_record, pdf_url, read_pdf

estimate, job, failure = read_pdf(client, "https://arxiv.org/pdf/1706.03762", max_pages=1)
print(f"{estimate.total_pages} pages in the PDF | parsing {estimate.pages_to_parse} | {estimate.credits} credit")
for page in job.pages:
    print("page", page.page_number, "|", page.method, "|", len(page.markdown), "characters")
print([line for line in job.pages[0].markdown.splitlines() if line.startswith("#")])

Output:

15 pages in the PDF | parsing 1 | 1 credit
page 1 | text | 2952 characters
['### Provided proper attribution is provided, Google hereby grants permission to', '## Attention Is All You Need', '#### Ashish Vaswani', '#### Llion Jones', '#### Illia Polosukhin', '### Abstract', '# arXiv:1706.03762v7 [cs.CL] 2 Aug 2023']

Read the page before you trust it

The page came back as Markdown, read from the page's own text. The headings show where layout leaks into structure: the author block comes out as three headings and a run of plain text, and the arXiv stamp appears as a top-level heading in the middle of the abstract. Page-level Markdown is raw material. Check a sample of pages before you build on it, and don't expect perfect tables, equations or multi-column layouts.

Save the metadata with its source link

citation() builds a reference string from the fields the search returned and leaves out any that are missing. build_record() puts the paper, its PDF link, how the parse went and the references into one record:

def citation(paper):
    """Built only from what the search returned. A missing field is left out, never guessed."""
    year = f"({paper.date[:4]})" if paper.date else None
    link = f"https://doi.org/{paper.doi}" if paper.doi else paper.url
    return " ".join(part for part in (paper.authors, year, paper.title, paper.source, link) if part)
def build_record(paper, pdf, note, estimate, job, failure):
    pages = [(p.page_number, p.markdown or "") for p in (job.pages if job else [])]
    return {**asdict(paper), "citation": citation(paper), "pdf_url": pdf, "pdf_note": note,
            "parse": None if not job else {
                "total_pages": job.total_pages, "pages_parsed": job.pages_parsed, "credits": job.credits_used,
                "methods": sorted({p.method for p in job.pages if p.method}),
                "pages_with_errors": [p.page_number for p in job.pages if p.error]},
            "references": references_from(pages) if job else None,
            "failure": failure}

A paper added by its link has no search metadata, so this record shows it: date and authors are null and the citation is just the title and link. Printing the record for the page above:

paper = Paper(title="Attention Is All You Need", url="https://arxiv.org/abs/1706.03762")
url, note = pdf_url(paper)
record = build_record(paper, url, note, estimate, job, failure)
keep = ("title", "date", "authors", "citation", "pdf_url", "pdf_note", "parse", "references", "failure")
print(json.dumps({key: record[key] for key in keep}, indent=2))

Output:

{
  "title": "Attention Is All You Need",
  "date": null,
  "authors": null,
  "citation": "Attention Is All You Need https://arxiv.org/abs/1706.03762",
  "pdf_url": "https://arxiv.org/pdf/1706.03762",
  "pdf_note": "derived from the arXiv link",
  "parse": {
    "total_pages": 15,
    "pages_parsed": 1,
    "credits": 1,
    "methods": [
      "text"
    ],
    "pages_with_errors": []
  },
  "references": {
    "found": false,
    "reason": "no References heading in the 1 parsed page(s)"
  },
  "failure": null
}

Find each paper's own references

A paper's reference list sits near the end, so it only appears if you parsed those pages. references_from() looks for a References heading in the pages you have, counts the entries after it, and says plainly when the heading isn't there:

HEADING = re.compile(r"^#{1,4}\s*(references|bibliography)\s*$", re.I | re.M)
ENTRY = re.compile(r"(?m)^\s*(?:[-*]\s*)?(?:\[\d+\]|\d+\.)\s+(.+)$")


def references_from(pages):
    """The paper's own reference list, if it falls inside the parsed pages. pages: [(number, markdown)]."""
    for number, text in pages:
        match = HEADING.search(text)
        if match:
            body = "\n".join([text[match.end():]] + [t for n, t in pages if n > number])
            return {"found": True, "page": number, "entries": ENTRY.findall(body)}
    return {"found": False, "reason": f"no References heading in the {len(pages)} parsed page(s)"}

For the page above it returns found: false with the reason, which is the right answer for page 1 of 15. To read the reference list, raise max_pages, or choose the last pages with pages, as the Parse docs describe. The entry pattern is simple, so spot-check the count against a paper before you rely on it.

Run the whole collection

collect() ties it together: search, choose, find the PDF, read it, and build a record per paper. save() writes one JSON line per paper and one Markdown file per parsed page, and report() prints what was skipped, what had no PDF and what failed:

# collect.py
import json
import re
from datetime import datetime, timezone
from pathlib import Path

from papers import build_record, coverage, pdf_url, read_pdf, select, to_paper


def collect(client, query, limit=10, keep=8, since=None, max_pages=12):
    """Search the research source, choose papers, and read the PDFs we have links for."""
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    found = client.search(query, sources=["research"], limit=limit)
    papers = [p for p in (to_paper(i, query, now) for i in found.data.research or []) if p]
    chosen, skipped = select(papers, since, keep)
    results = []
    for paper in chosen:
        url, note = pdf_url(paper)
        if url is None:
            results.append((build_record(paper, None, note, None, None, "no PDF link in the search result"), None))
            continue
        estimate, job, failure = read_pdf(client, url, max_pages)
        results.append((build_record(paper, url, note, estimate, job, failure), job))
    return papers, chosen, skipped, results
def save(folder, results):
    """One JSON line per paper, and one Markdown file per parsed page."""
    base = Path(folder)
    with open(base / "papers.jsonl", "w", encoding="utf-8") as out:
        for record, job in results:
            out.write(json.dumps(record, ensure_ascii=False) + "\n")
            for page in job.pages if job else []:
                slug = re.sub(r"[^a-z0-9]+", "-", record["title"].lower())[:50].strip("-")
                (base / "pages" / slug).mkdir(parents=True, exist_ok=True)
                (base / "pages" / slug / f"page-{page.page_number:03d}.md").write_text(page.markdown or "", encoding="utf-8")


def report(papers, chosen, skipped, results):
    print(len(papers), "results,", len(chosen), "chosen,", len(skipped), "skipped")
    for source, row in coverage(papers).items():
        print(" ", source.ljust(8), row)
    for title, reason in skipped:
        print("  skipped:", title, "|", reason)
    for record, _ in results:
        parse = record["parse"]
        outcome = (record["failure"] or f"{parse['pages_parsed']} of {parse['total_pages']} pages, "
                   f"references found: {record['references']['found']}")
        print("-", record["title"], "|", outcome)

Keep papers.jsonl together with the pages. Each record holds the query, the date it was retrieved and the paper's links, so when a later search returns different results you can still re-run the parse step on the same papers.

Run it:

papers, chosen, skipped, results = collect(client, QUERY, limit=10, keep=8, max_pages=12)
report(papers, chosen, skipped, results)
save(".", results)

Output:

[NEED: output of the full run on the ten results: counts per source, every skipped paper with its reason, and one line per chosen paper with pages parsed, references found, no PDF link or the failure]

Test the rules

These tests pin the rules that are easiest to get wrong: the missing fields, the PDF links, the skip reasons and the reference list. The search results in them are hand-written for testing:

# test_papers.py
from types import SimpleNamespace as NS

from papers import pdf_url, references_from, select, to_paper

NOW = "2026-11-25T12:00:00+00:00"


def item(**fields):
    """Hand-written search results for testing the rules. Not API output."""
    base = dict(title="A title", url="https://arxiv.org/abs/2301.00001", position=1, description=None,
                source="arXiv", date="2023-01-02T00:00:00Z", authors=None, doi=None)
    return NS(**(base | fields))


def test_a_missing_field_stays_none_and_a_title_is_not_borrowed():
    paper = to_paper(item(), "q", NOW)
    assert paper.authors is None and paper.doi is None and paper.abstract is None


def test_only_links_the_result_supports_become_pdf_links():
    arxiv = to_paper(item(), "q", NOW)
    pubmed = to_paper(item(url="https://doi.org/10.3389/frai.2024.1366273", source="PubMed"), "q", NOW)
    assert pdf_url(arxiv) == ("https://arxiv.org/pdf/2301.00001", "derived from the arXiv link")
    assert pdf_url(pubmed) == (None, "doi.org link is a landing page, not a PDF")


def test_every_skipped_paper_has_a_reason():
    papers = [to_paper(item(title="One", doi="10.1/a"), "q", NOW),
              to_paper(item(title="One again", doi="10.1/A", url="https://arxiv.org/abs/2301.00002"), "q", NOW),
              to_paper(item(title="Old", date="2019-05-01", url="https://arxiv.org/abs/1905.00001"), "q", NOW),
              to_paper(item(title="Two", url="https://arxiv.org/abs/2301.00003"), "q", NOW),
              to_paper(item(title="Three", url="https://arxiv.org/abs/2301.00004"), "q", NOW)]
    chosen, skipped = select(papers, since="2021-01-01", keep=2)
    assert [p.title for p in chosen] == ["One", "Two"]
    assert dict(skipped) == {"One again": "same paper as an earlier result", "Old": "published before 2021-01-01",
                             "Three": "beyond the first 2"}


def test_references_are_found_only_inside_the_parsed_pages():
    pages = [(5, "Body text.\n\n## References\n\n[1] A. Author. A title. 2020.\n[2] B. Author. Another title. 2021."),
             (6, "[3] C. Author. A third title. 2022.")]
    found = references_from(pages)
    assert found["found"] and found["page"] == 5 and len(found["entries"]) == 3
    assert references_from(pages[:0] + [(1, "Abstract only.")]) == {"found": False, "reason": "no References heading in the 1 parsed page(s)"}

Output:

$ pytest -q
....                                                                     [100%]
4 passed in 0.11s

Conclusion

You now have a pipeline that turns a topic into source-linked paper records: found, chosen with stated reasons, read into page-level Markdown, and saved with the failures and gaps in plain view. Research products need both halves, discovery and document ingestion, and Spidra puts them in one account:

  • Discovery and ingestion in one place. Search the research source for papers, then parse their PDFs, with one credit balance and one SDK.
  • Know the cost first. A Parse estimate is free and gives the page count and credits before you spend any, and it lets you parse by file_id without fetching the file twice.
  • Page-level output you can inspect. Every page says how it was read: from its own text, or with AI for scanned pages.
  • Failures are free. A document that can't be parsed costs nothing and says why.
  • It scales past a sample. Parse takes up to 50 documents per batch, reads DOCX, EPUB and other formats too, and sits next to Scrape and Crawl for the landing pages that PDFs don't cover.

Every plan has every feature, and the dashboard's Code button writes the request for whatever you set up. Create a free account, set SPIDRA_API_KEY, and run collect.py on a topic you care about.

Frequently asked questions

Install the Spidra SDK, create a client, and call search with the research source. You get titles, links, short descriptions and, when the source has them, dates, authors and DOIs. Then choose the papers you want and parse their PDFs.

Share this article

You build the product.
Spidra handles the data work.

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