Skip to main content
TutorialsDecember 1, 2026 · 12 min read

How to extract every relevant article from a blog with Python

Find a blog's article URLs, tell posts from category and archive pages, extract each into one schema and save a structured archive with Python.

How to extract every relevant article from a blog with Python

You want every article from a blog as one structured record: title, author, date, text, URL and categories. The hard part isn't reading a post. It's deciding which pages are posts, because a blog is also full of category pages, tag pages, pagination and the index, and a crawler returns all of them. This tutorial finds a blog's URLs, keeps only the articles, extracts each one with the same schema, and saves a structured archive in Python.

We'll use the Spidra blog, which is ours and permits this. For any other blog, check its terms first and read our guide to the legal side of scraping. If you haven't used the Spidra Python SDK, the Python tutorial covers the install and your API key.

Check whether the blog already publishes a feed

Many blogs publish an RSS or Atom feed, and a sitemap. If a feed carries full posts, read it with feedparser and stop here. This script checks the usual addresses:

# check_feeds.py
import requests

SITE = "https://spidra.io"
for path in ("/feed", "/rss.xml", "/atom.xml", "/blog/rss.xml", "/sitemap.xml"):
    response = requests.get(SITE + path, timeout=15)
    print(path, response.status_code, response.headers.get("content-type"))

When the feed is missing, cuts posts to a summary, or doesn't list older posts, you need to find the pages yourself. That's the rest of this tutorial.

Map the blog and see what it contains

Map lists a site's URLs from its sitemap and its page links, without reading the pages. For how Map and a batch scrape fit together, see Map a website and scrape only the pages you need. Here the script starts by mapping the blog and sorting every URL by what it is:

import csv
import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from urllib.parse import urljoin, urlparse

from spidra import BatchScrapeParams, Spidra

NAV_PREFIXES = ("category/", "tag/", "author/", "page/")
SCHEMA = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "author": {"type": ["string", "null"]},
        "published": {"type": ["string", "null"], "description": "Publication date exactly as shown on the page"},
        "updated": {"type": ["string", "null"], "description": "Last-updated date exactly as shown, if the page has one"},
    },
}
DATE_FORMATS = ("%B %d, %Y", "%b %d, %Y", "%d %B %Y", "%Y-%m-%d", "%Y/%m/%d")
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
mapped = client.map(blog, limit=500)

kinds = {}
for link in mapped.links:
    kinds.setdefault(classify(link.url, blog), {}).setdefault(dedupe_key(link.url), link.url)
print(len(mapped.links), "URLs mapped")
for kind, urls in sorted(kinds.items()):
    print(f"  {kind:<10} {len(urls)}")

archive = Path("archive.jsonl")
seen = {dedupe_key(json.loads(line)["url"]) for line in archive.read_text().splitlines()} if archive.exists() else set()
todo = [url for key, url in kinds.get("article", {}).items() if key not in seen]
print(len(todo), "new articles to extract")

Map finds what the sitemap and the site's links expose, so it isn't a guarantee that it found every post.

Tell articles from navigation pages

A blog's URLs are mostly not articles. A ten-page crawl of the Spidra blog with the instruction "All pages" returns the blog index, six category pages and three posts. With the instruction "Individual blog posts" it returns ten posts. Map has no instruction, so we sort the URLs ourselves with a rule that depends only on the path:

def classify(url, blog):
    """Say what kind of page a URL is: article, category, pagination, index or outside."""
    base, page = urlparse(blog), urlparse(url)
    path, base_path = page.path.rstrip("/"), base.path.rstrip("/")
    if page.netloc != base.netloc or not (path == base_path or path.startswith(base_path + "/")):
        return "outside"
    rest = path[len(base_path):].strip("/")
    if "page=" in page.query or rest.startswith("page/"):
        return "pagination"
    if not rest:
        return "index"
    if rest.startswith(NAV_PREFIXES):
        return "category" if rest.startswith(("category/", "tag/")) else "other"
    return "article" if "/" not in rest else "other"

Run it on a few URLs. The last two are made up to show the pagination and tag rules:

from blog_archive import classify

BLOG = "https://spidra.io/blog"
for url in [
    "https://spidra.io/blog",
    "https://spidra.io/blog/category/tutorials",
    "https://spidra.io/blog/category/trends",
    "https://spidra.io/blog/spidra-search-api",
    "https://spidra.io/blog/map-website-batch-scrape-selected-pages",
    "https://spidra.io/pricing",
    "https://spidra.io/blog?page=2",
    "https://spidra.io/blog/tag/python",
]:
    print(f"{classify(url, BLOG):<11}{url}")

Output:

index      https://spidra.io/blog
category   https://spidra.io/blog/category/tutorials
category   https://spidra.io/blog/category/trends
article    https://spidra.io/blog/spidra-search-api
article    https://spidra.io/blog/map-website-batch-scrape-selected-pages
outside    https://spidra.io/pricing
pagination https://spidra.io/blog?page=2
category   https://spidra.io/blog/tag/python

The rule is a guess about this blog's URL layout: an article is one path segment under /blog, and the first segment of a navigation page is category, tag, author or page. Change NAV_PREFIXES for a blog that lays its pages out differently, and check the counts against a few pages you know.

Remove duplicate URLs

The same post can come back with a trailing slash, a www prefix or tracking parameters. dedupe_key reduces a URL to its host and path, and the script keeps one URL per key:

def dedupe_key(url):
    """The same post can appear with a trailing slash, a www prefix or tracking parameters."""
    page = urlparse(url)
    return page.netloc.lower().removeprefix("www.") + page.path.rstrip("/")
from blog_archive import dedupe_key

for url in [
    "https://spidra.io/blog/spidra-search-api",
    "https://www.spidra.io/blog/spidra-search-api/",
    "https://spidra.io/blog/spidra-search-api?utm_source=newsletter",
]:
    print(dedupe_key(url))

Output:

spidra.io/blog/spidra-search-api
spidra.io/blog/spidra-search-api
spidra.io/blog/spidra-search-api

Extract the same fields from every article

Batch scrape takes up to 50 URLs per request and gives each one its own result. With a schema, every article's result is an object with the same fields. Fields a page may not have are nullable, and the dates are requested exactly as shown, so the page's own text is what's stored:

def scrape_all(client, urls, **options):
    """Batch scrape in chunks of 50. Returns {dedupe_key: item}."""
    items = {}
    for i in range(0, len(urls), 50):
        response = client.batch_scrape(BatchScrapeParams(urls=urls[i:i + 50], **options))
        items.update({dedupe_key(item.url): item for item in response.items})
    return items

The two passes in the script reuse that helper. The first uses the schema (title, author, published, updated), and the second returns each article's clean text, which we'll cover in a moment:

fields = scrape_all(client, todo, schema=SCHEMA)
texts = scrape_all(client, todo, extract_content_only=True)
categories = categories_from(scrape_all(client, list(kinds.get("category", {}).values()), extract_content_only=True), blog)

Take the text from the page, not from the schema

The schema could include a text field, but then the model has to write out every word of every post. That's slow, costs more, and can shorten long articles. extract_content_only=True returns the page's own Markdown with the menu, header and footer removed, so the text is the page's own, word for word. The two results are joined by URL.

Get the categories from the category pages

A post page doesn't show its own category. On the Spidra blog a schema field for it comes back null or "Blog", because a schema can only return what's on the page. The category pages do list their posts, so they're where categories come from. They're navigation pages and not articles, which is why we kept them:

def categories_from(category_pages, blog):
    """Category pages list their posts, so they are where categories come from."""
    found = {}
    for url, item in category_pages.items():
        name = url.rstrip("/").rsplit("/", 1)[-1].replace("-", " ").title()
        for href in re.findall(r"\]\(([^)\s]+)\)", item.result or ""):
            link = urljoin(item.url, href)
            if classify(link, blog) == "article":
                found.setdefault(dedupe_key(link), set()).add(name)
    return found

Every link on a category page that classifies as an article gets that category's name, so a post in two categories collects both.

Normalize the dates and flag the odd ones

Blogs print dates in whatever format the template uses, some posts have no date, and a few have an "updated" date. parse_date turns the common formats into an ISO date and returns None for the rest:

def parse_date(text):
    """Return an ISO date for the common formats, or None."""
    if not text:
        return None
    for fmt in DATE_FORMATS:
        try:
            return datetime.strptime(text.strip(), fmt).date().isoformat()
        except ValueError:
            pass
    return None
from blog_archive import parse_date

for text in ["September 30, 2026", "October 15, 2026", "October 2, 2026", "Oct 15, 2026", "2026-10-15", "Sept 30th, 2026", None]:
    print(repr(text), "->", parse_date(text))

Output:

'September 30, 2026' -> 2026-09-30
'October 15, 2026' -> 2026-10-15
'October 2, 2026' -> 2026-10-02
'Oct 15, 2026' -> 2026-10-15
'2026-10-15' -> 2026-10-15
'Sept 30th, 2026' -> None
None -> None

The first three strings are dates as the Spidra blog shows them. The rest are formats you'll meet on other blogs. A date that can't be read isn't dropped. The record keeps the original text and a date_status, so you can see what needs a second look:

def build_record(url, fields, text, categories):
    published = parse_date(fields.get("published"))
    updated = parse_date(fields.get("updated"))
    if not fields.get("published"):
        status = "missing"
    elif not published:
        status = "unparsed"
    elif updated and updated < published:
        status = "updated_before_published"
    else:
        status = "ok"
    return {
        "url": url, "title": fields.get("title"), "author": fields.get("author"),
        "published": published, "published_text": fields.get("published"), "updated": updated,
        "date_status": status, "categories": sorted(categories), "words": len((text or "").split()), "text": text,
    }

ok, missing, unparsed and updated_before_published cover what a quick check will find. Anything but ok is worth reading before you analyze by date.

Save the archive and run it again

The last part of the script drops failed pages from the archive, appends new records to archive.jsonl, and rewrites archive.csv from everything stored:

records, failed = [], []
for url in todo:
    key = dedupe_key(url)
    if fields[key].status != "completed" or texts[key].status != "completed":
        failed.append((url, fields[key].error or texts[key].error))
        continue
    records.append(build_record(url, fields[key].result, texts[key].result, categories.get(key, [])))

with archive.open("a", encoding="utf-8") as out:
    for record in records:
        out.write(json.dumps(record, ensure_ascii=False) + "\n")
all_records = [json.loads(line) for line in archive.read_text().splitlines()]
with open("archive.csv", "w", newline="", encoding="utf-8") as out:
    writer = csv.writer(out)
    writer.writerow(["title", "author", "published", "updated", "categories", "url", "words"])
    for r in all_records:
        writer.writerow([r["title"], r["author"], r["published"], r["updated"], "; ".join(r["categories"]), r["url"], r["words"]])
print(f"saved {len(records)} articles, {len(failed)} failed")
for url, error in failed:
    print("  failed:", url, "-", error)

The script reads archive.jsonl before it extracts anything, so a second run only fetches articles it hasn't stored. A page that failed isn't saved, so the next run tries it again. Failed pages aren't charged. Run it:

python blog_archive.py https://spidra.io/blog

JSONL keeps the full text and every field, one article per line. The CSV leaves the text out and adds a word count, which is easier to open in a spreadsheet.

Use Crawl when there's no sitemap

Map reads a sitemap and the links on a page. When a blog has neither a sitemap nor links to its older posts, a crawl follows links toward the pages you describe. You write the instruction ("Individual blog posts") and a schema, and each matching page comes back with its data. Pages read only to get to others, such as category and listing pages, are navigation pages and aren't returned:

# blog_articles.py
import os
import time
from spidra import CrawlParams, Spidra

client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])

queued = client.start_crawl(CrawlParams(
    base_url="https://spidra.io/blog",
    crawl_instruction="Individual blog posts",
    schema={
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "author": {"type": "string"},
            "published": {"type": "string"},
        },
    },
    max_pages=5,
))

job = client.get_crawl(queued.job_id)
while job.status not in ("completed", "failed", "cancelled"):
    time.sleep(5)
    job = client.get_crawl(queued.job_id)

for page in job.result:
    print(page.url, "|", page.data)

report = client.crawl_report(queued.job_id).report
print("understood as:", report.understood_as)
print("navigation pages:", report.navigation_pages, "| skipped:", report.skipped_total)
for reason in report.skipped:
    print(" ", reason.reason, reason.count)
print("job id:", queued.job_id)

Output:

https://spidra.io/blog/spidra-search-api | {'title': 'Introducing Spidra Search: Search the web before you scrape it', 'author': 'Joel Olawanle', 'published': 'September 30, 2026'}
https://spidra.io/blog/map-website-batch-scrape-selected-pages | {'title': 'How to map a website and scrape only the pages you need', 'author': 'Joel Olawanle', 'published': 'October 15, 2026'}
https://spidra.io/blog/scrape-multiple-urls-python | {'title': 'How to scrape multiple URLs in Python and handle failures', 'author': 'Joel Olawanle', 'published': 'October 15, 2026'}
https://spidra.io/blog/how-to-scrape-pdf-extract-json-api | {'title': 'How to Scrape PDFs and Extract Structured JSON with an API', 'author': 'Joel Olawanle', 'published': 'October 2, 2026'}
https://spidra.io/blog/best-web-search-apis-ai-agents | {'title': 'Search API vs scraping API: when you need one, the other, or both', 'author': 'Joel Olawanle', 'published': 'September 30, 2026'}
understood as: Individual blog post articles.
navigation pages: 1 | skipped: 46
  outside_domain 26
  not_relevant 20
job id: 9a9ae00c-672e-4a3a-8982-1f4b554febe6

start_crawl() returns the job ID that crawl_report() needs. The report says how the instruction was understood and why other pages were skipped, which answers "why didn't it return that post?".

Two things to know before you choose Crawl over Map. A crawl returns each page's whole Markdown, navigation included, and has no "extract content only" option, so you'd strip the menu yourself. And the category has the same problem as before: a post page doesn't show it.

What this doesn't handle

  • A site's permission. The Spidra blog is ours. For any other blog, read its terms and robots.txt first. Map and Crawl can skip pages that robots.txt disallows with respect_robots, and our legal guide covers the rest.
  • "Load more" buttons and infinite scroll. A blog that loads older posts with a click needs browser actions before the links appear.
  • Paywalls and logins. Spidra can use your own session cookies, and you're responsible for the account.
  • A complete list. Map finds what the sitemap and links expose. A post with no link to it and no sitemap entry won't appear.
  • Other URL layouts. The classifier is a rule about one blog's paths. Check its counts against a few pages you know.
  • Republishing. An archive of text is for research and analysis. Copyright still applies to the posts.

Conclusion

You built an archive of every article on a blog: a Map call to find the URLs, a classifier that keeps posts and sets navigation pages aside, one schema for every article, clean text for each, categories joined from the category pages, dates normalized and flagged, and duplicates removed. Run it again and it only fetches what's new.

Spidra does the part that's hard to do yourself. Map lists a whole site in one call. Batch scrape reads up to 50 pages per request and gives each its own result, with a failed page reported and free, so one bad URL doesn't stop the run. A schema returns the same typed fields from every page, and extract-content-only returns the article without the menu. When there's no sitemap, Crawl takes a plain-language instruction like "Individual blog posts" and its report explains every skipped page. Pages are read in a real browser, so blogs that build their pages with JavaScript can be read too, and browser actions handle the "load more" button.

The same key reaches further. Search finds pages across web and news before you read them, Parse turns PDFs and Office files into Markdown, and over 90 ready-made templates return tables for popular sites. Every plan includes every feature, with the plans differing in credits, proxy bandwidth, pages per crawl and monitors, so the archive you build on a free account is the one you can run for a content or research product that needs the same structured source again and again. Official SDKs cover ten languages, and an MCP server lets AI tools use the same account.

Create a free account at app.spidra.io, set SPIDRA_API_KEY, and run blog_archive.py on a blog you're allowed to archive.

Frequently asked questions

Start with the blog's feed and sitemap, which many blogs publish. If they're missing or incomplete, Map lists a site's URLs from its sitemap and page links in one call, and a crawl follows links toward the pages you describe. Then sort the URLs, because the list includes category, tag and pagination pages as well as posts.

Share this article

You build the product.
Spidra handles the data work.

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