"""
Simple news scraper + summarizer.
Before using this script:
- Check the website's Terms of Service and robots.txt.
- Scrape responsibly: limit your request rate and avoid overloading servers.
- Replace BASE_LISTING_URL and CSS selectors with ones that match your target site.
Install dependencies:
pip install requests beautifulsoup4
"""
import time
import re
from collections import Counter
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
# ---------- Configuration ----------
BASE_LISTING_URL = "https://example.com/news" # <-- change this
HEADERS = {
"User-Agent": "Mozilla/5.0 (compatible; NewsScraper/1.0; +https://your-domain.example)"
}
# How many sentences to keep in the summary
SUMMARY_SENTENCES = 3
# Pause between HTTP requests (seconds)
REQUEST_DELAY = 1.0
# A small list of English stopwords for summarization.
STOPWORDS = {
"the", "and", "a", "an", "of", "to", "in", "on", "for", "is", "are", "was",
"were", "be", "been", "being", "it", "that", "this", "with", "as", "by",
"at", "from", "or", "if", "but", "about", "into", "up", "down", "out",
"over", "under", "again", "further", "then", "once", "here", "there",
"when", "where", "why", "how", "all", "any", "both", "each", "few",
"more", "most", "other", "some", "such", "no", "nor", "not", "only",
"own", "same", "so", "than", "too", "very", "can", "will", "just",
"should", "could", "would", "may", "might", "do", "does", "did",
"have", "has", "had", "you", "your", "yours", "he", "him", "his",
"she", "her", "they", "them", "their", "theirs", "we", "us", "our",
"ours", "i", "me", "my", "mine"
}
# ---------- Scraping Functions ----------
def fetch_html(url: str) -> str:
"""Fetch the raw HTML for a given URL."""
resp = requests.get(url, headers=HEADERS, timeout=15)
resp.raise_for_status()
return resp.text
def fetch_article_links(listing_url: str) -> list[str]:
"""
Extract article links from a listing page.
You MUST customize the CSS selector (soup.select('h2 a')) to match your site.
Common patterns:
- 'h2 a' (link inside article headline)
- '.post-title a'
- 'article a'
"""
html = fetch_html(listing_url)
soup = BeautifulSoup(html, "html.parser")
links = set()
for a in soup.select("h2 a"): # <--- change this selector for your site
href = a.get("href")
if not href:
continue
full_url = urljoin(listing_url, href)
links.add(full_url)
return sorted(links)
def fetch_article_content(url: str) -> tuple[str, str]:
"""
Download a single article page and extract title + main text.
You may need to customize the `selectors` list to match the site's structure.
"""
html = fetch_html(url)
soup = BeautifulSoup(html, "html.parser")
# Try to get the main title
title_tag = soup.find("h1")
title = title_tag.get_text(strip=True) if title_tag else url
# Try several common containers for article body
selectors = [
"article p",
".post-content p",
".entry-content p",
".article-body p",
]
paragraphs = []
for sel in selectors:
paragraphs = [p.get_text(" ", strip=True) for p in soup.select(sel)]
if paragraphs:
break
# Fallback: just grab all <p> tags
if not paragraphs:
paragraphs = [p.get_text(" ", strip=True) for p in soup.find_all("p")]
text = " ".join(p for p in paragraphs if p)
return title, text
# ---------- Summarization ----------
def summarize_text(text: str, max_sentences: int = 3) -> str:
"""
Simple extractive summarizer:
- Split text into sentences
- Score sentences by word frequency (ignoring stopwords)
- Return the top N sentences in original order
"""
# Split into sentences using a simple regex
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
if not sentences:
return ""
if len(sentences) <= max_sentences:
return text
# Count word frequencies
word_freq = Counter()
for sent in sentences:
words = re.findall(r"\w+", sent.lower())
for w in words:
if w in STOPWORDS or len(w) < 3:
continue
word_freq[w] += 1
if not word_freq:
# Fallback: just return the first N sentences
return " ".join(sentences[:max_sentences])
# Score sentences
scored = []
for idx, sent in enumerate(sentences):
words = re.findall(r"\w+", sent.lower())
score = sum(word_freq.get(w, 0) for w in words)
scored.append((score, idx, sent))
# Take top N by score, then restore original order
top = sorted(scored, key=lambda x: (-x[0], x[1]))[:max_sentences]
top_sorted = sorted(top, key=lambda x: x[1])
summary = " ".join(s for _, _, s in top_sorted)
return summary
# ---------- Main Orchestration ----------
def main():
# For a single listing page:
listing_urls = [BASE_LISTING_URL]
# If your site uses pagination like ?page=2, uncomment and adapt:
# listing_urls = [f"{BASE_LISTING_URL}?page={i}" for i in range(1, 4)]
seen_articles = set()
for listing_url in listing_urls:
print(f"\nFetching listing page: {listing_url}")
try:
article_links = fetch_article_links(listing_url)
except Exception as e:
print(f" Error fetching listing: {e}")
continue
print(f" Found {len(article_links)} article links")
for link in article_links:
if link in seen_articles:
continue
seen_articles.add(link)
print(f"\nDownloading article: {link}")
try:
title, text = fetch_article_content(link)
except Exception as e:
print(f" Error fetching article: {e}")
continue
if not text.strip():
print(" Skipping (no text found).")
continue
summary = summarize_text(text, max_sentences=SUMMARY_SENTENCES)
print("=" * 80)
print("Title :", title)
print("URL :", link)
print("\nSummary:")
print(summary)
print("=" * 80)
# Be polite to the server
time.sleep(REQUEST_DELAY)
if __name__ == "__main__":
main()