A personal news aggregator is one of the most immediately useful things you can build with a scraper and an LLM: collect articles from the sources you care about, surface the important ones, deduplicate overlapping coverage, and generate a daily digest you can actually read in 5 minutes.
This guide builds a complete Python news aggregator: RSS-first collection with full-article fallback via UnWeb, content deduplication using title similarity and URL normalization, Claude-powered summarization, and SQLite storage with a daily digest generator.
Architecture Overview
- Collection: Parse RSS/Atom feeds for headlines and URLs; use UnWeb to fetch full article content when needed
- Storage: Persist articles to SQLite with deduplication at ingestion time
- Ranking: Filter to relevant articles based on configured topics
- Summarization: Batch-summarize selected articles with Claude Haiku
- Digest generation: Produce a formatted daily digest (Markdown or email)
Data Models
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional
@dataclass
class Source:
name: str
rss_url: str
topics: list[str] # Keywords for relevance filtering
@dataclass
class Article:
url: str
title: str
source: str
published_at: datetime
summary: Optional[str] = None # LLM-generated summary
full_content: Optional[str] = None # Full Markdown content from UnWeb
relevance_score: float = 0.0
topics_matched: list[str] = field(default_factory=list)
@dataclass
class DigestEntry:
article: Article
one_liner: str # 1-sentence summary for the digest
RSS Collection
import feedparser
import httpx
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
async def fetch_rss_articles(source: Source) -> list[Article]:
"""Fetch articles from an RSS/Atom feed."""
feed = feedparser.parse(source.rss_url)
articles = []
for entry in feed.entries:
# Parse publish date
published_at = datetime.now(timezone.utc)
if hasattr(entry, 'published'):
try:
published_at = parsedate_to_datetime(entry.published)
except Exception:
pass
elif hasattr(entry, 'updated'):
try:
published_at = parsedate_to_datetime(entry.updated)
except Exception:
pass
# Get the best available URL
url = getattr(entry, 'link', None)
if not url:
continue
# RSS often includes a short summary in the feed
rss_summary = getattr(entry, 'summary', '') or getattr(entry, 'description', '')
articles.append(Article(
url=url,
title=entry.title.strip(),
source=source.name,
published_at=published_at,
summary=rss_summary[:500] if rss_summary else None,
))
return articles
Full-Article Fetch via UnWeb
RSS feeds often contain only headlines and short teasers. For meaningful summarization, you need the full article text. UnWeb handles paywall-free news sites well — converting articles to clean Markdown without ads, nav bars, or comment sections:
UNWEB_API_KEY = "your_api_key"
async def fetch_full_article(url: str, client: httpx.AsyncClient) -> Optional[str]:
"""Fetch full article content as Markdown via UnWeb."""
try:
response = await client.get(
"https://api.unweb.info/v1/convert",
params={"url": url},
headers={"Authorization": f"Bearer {UNWEB_API_KEY}"},
timeout=30.0,
)
response.raise_for_status()
markdown = response.json()["markdown"]
# Trim to first 3000 words to control summarization costs
words = markdown.split()
if len(words) > 3000:
markdown = ' '.join(words[:3000]) + "\n\n[Article truncated]"
return markdown
except Exception as e:
return None # Fall back to RSS summary
SQLite Storage with Deduplication
import sqlite3
import re
from difflib import SequenceMatcher
def init_db(db_path: str = "news.db") -> sqlite3.Connection:
conn = sqlite3.connect(db_path)
conn.execute("""
CREATE TABLE IF NOT EXISTS articles (
url TEXT PRIMARY KEY,
title TEXT NOT NULL,
source TEXT NOT NULL,
published_at TEXT NOT NULL,
summary TEXT,
full_content TEXT,
relevance_score REAL DEFAULT 0.0,
topics_matched TEXT,
digest_included INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_articles_published ON articles (published_at DESC)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_articles_source ON articles (source)")
conn.commit()
return conn
def normalize_title(title: str) -> str:
"""Normalize a title for similarity comparison."""
return re.sub(r'[^\w\s]', '', title.lower()).strip()
def is_duplicate(conn: sqlite3.Connection, article: Article, threshold: float = 0.85) -> bool:
"""Check if a similar article already exists (same story, different source)."""
# First check: exact URL match
row = conn.execute("SELECT 1 FROM articles WHERE url = ?", (article.url,)).fetchone()
if row:
return True
# Second check: title similarity for same-day articles
today_articles = conn.execute(
"""SELECT title FROM articles
WHERE published_at >= date('now', '-1 day')""",
).fetchall()
normalized_new = normalize_title(article.title)
for (existing_title,) in today_articles:
normalized_existing = normalize_title(existing_title)
similarity = SequenceMatcher(None, normalized_new, normalized_existing).ratio()
if similarity >= threshold:
return True
return False
def save_article(conn: sqlite3.Connection, article: Article) -> bool:
"""Save article to database. Returns False if it was a duplicate."""
if is_duplicate(conn, article):
return False
conn.execute(
"""INSERT OR IGNORE INTO articles
(url, title, source, published_at, summary, full_content, relevance_score, topics_matched)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(
article.url,
article.title,
article.source,
article.published_at.isoformat(),
article.summary,
article.full_content,
article.relevance_score,
','.join(article.topics_matched),
)
)
conn.commit()
return True
Relevance Filtering
def score_relevance(article: Article, watch_topics: list[str]) -> tuple[float, list[str]]:
"""
Score an article's relevance to configured topics.
Returns (score, matched_topics).
"""
text = f"{article.title} {article.summary or ''}".lower()
matched = []
for topic in watch_topics:
topic_words = topic.lower().split()
# Phrase match: all words in the topic must appear in the text
if all(word in text for word in topic_words):
matched.append(topic)
# Simple scoring: number of matched topics / total topics
score = len(matched) / len(watch_topics) if watch_topics else 0.0
return score, matched
Claude-Powered Summarization
import anthropic
import json
client_ai = anthropic.Anthropic()
def summarize_articles(articles: list[Article]) -> list[tuple[Article, str]]:
"""
Batch-summarize a list of articles.
Returns list of (article, one_liner) tuples.
"""
if not articles:
return []
# Build a batch prompt to summarize multiple articles in one API call
articles_text = "\n\n---\n\n".join([
f"Article {i+1}:\nTitle: {a.title}\nSource: {a.source}\n\nContent:\n{a.full_content or a.summary or 'No content available'}"
for i, a in enumerate(articles)
])
message = client_ai.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=2048,
messages=[{
"role": "user",
"content": f"""Summarize each of these news articles in one clear, informative sentence (15-25 words).
Focus on the key fact or development. Be specific — avoid vague summaries.
Return a JSON array with one string per article, in the same order.
Example: ["Summary of article 1.", "Summary of article 2."]
Articles:
{articles_text}"""
}]
)
try:
raw = message.content[0].text.strip()
# Extract JSON array from response
json_match = re.search(r'\[.*\]', raw, re.DOTALL)
if json_match:
summaries = json.loads(json_match.group(0))
return list(zip(articles, summaries))
except (json.JSONDecodeError, IndexError):
pass
# Fallback: return articles with their RSS summary as the one-liner
return [(a, (a.summary or a.title)[:120]) for a in articles]
Batching to reduce API costs: Summarizing 10 articles in one API call costs far less than 10 individual calls. Claude Haiku is used here for cost efficiency — for higher-quality summaries on important topics, swap in a larger model.
Daily Digest Generator
from datetime import date
def generate_digest(
conn: sqlite3.Connection,
watch_topics: list[str],
max_articles: int = 15,
) -> str:
"""Generate a Markdown daily digest from today's top articles."""
# Get today's articles, ranked by relevance
rows = conn.execute(
"""SELECT url, title, source, published_at, summary, topics_matched, relevance_score
FROM articles
WHERE published_at >= date('now', '-1 day')
AND relevance_score > 0
ORDER BY relevance_score DESC, published_at DESC
LIMIT ?""",
(max_articles,)
).fetchall()
if not rows:
return f"# Daily Digest — {date.today()}\n\nNo relevant articles found today."
# Group by matched topics
by_topic: dict[str, list] = {}
for row in rows:
url, title, source, published_at, summary, topics_matched, score = row
topics = topics_matched.split(',') if topics_matched else ['Other']
primary_topic = topics[0]
if primary_topic not in by_topic:
by_topic[primary_topic] = []
by_topic[primary_topic].append((title, url, source, summary))
# Build Markdown digest
lines = [f"# Daily Digest — {date.today()}", ""]
for topic, articles in by_topic.items():
lines.append(f"## {topic.title()}")
for title, url, source, summary in articles:
lines.append(f"**[{title}]({url})** — *{source}*")
if summary:
lines.append(f"> {summary[:150]}{'...' if len(summary) > 150 else ''}")
lines.append("")
return '\n'.join(lines)
Putting It All Together
import asyncio
import schedule
import time
SOURCES = [
Source("TechCrunch", "https://techcrunch.com/feed/", ["AI", "startup", "funding"]),
Source("Hacker News", "https://hnrss.org/frontpage", ["programming", "python", "AI", "startup"]),
Source("The Verge", "https://www.theverge.com/rss/index.xml", ["AI", "software"]),
]
WATCH_TOPICS = ["AI", "machine learning", "python", "startup", "open source"]
async def run_collection(conn: sqlite3.Connection) -> None:
new_articles = []
async with httpx.AsyncClient() as client:
# Collect from all sources
for source in SOURCES:
articles = await fetch_rss_articles(source)
for article in articles:
score, matched = score_relevance(article, WATCH_TOPICS)
article.relevance_score = score
article.topics_matched = matched
if score > 0 and not is_duplicate(conn, article):
# Fetch full content for relevant articles
full_content = await fetch_full_article(article.url, client)
if full_content:
article.full_content = full_content
new_articles.append(article)
await asyncio.sleep(1.0) # Polite delay
# Summarize new articles
if new_articles:
summarized = summarize_articles(new_articles[:20]) # Batch max 20
for article, one_liner in summarized:
article.summary = one_liner
save_article(conn, article)
print(f"Added {len(new_articles)} new articles")
# Generate daily digest
digest = generate_digest(conn, WATCH_TOPICS)
with open("digest.md", "w") as f:
f.write(digest)
print("Digest written to digest.md")
conn = init_db()
asyncio.run(run_collection(conn))
# Schedule to run every 3 hours
schedule.every(3).hours.do(lambda: asyncio.run(run_collection(conn)))
while True:
schedule.run_pending()
time.sleep(60)
Extract clean article content from any news site
UnWeb converts any web page — including JS-rendered news sites — to clean Markdown. No ads, no nav bars, just the article. Free tier available.
Extensions Worth Adding
- Email digest: Use smtplib to send the Markdown digest as an HTML email with
markdown2 - Slack digest: Post formatted summaries to a Slack channel via webhook
- Topic clustering: Use Claude to group articles by story (same event, different angles) rather than just keyword matching
- Importance scoring: Ask Claude to rate the importance of each article (1–5) based on the configured topics, then filter the digest to only 4+ scored items
- Web interface: Serve the SQLite database via FastAPI with a simple Jinja2 template for browsing articles