Explore Generate Python code to scrape and summarize news articles from a website. Save Share Download ▾ ReportGenerate Python code to scrape and summarize news articles from a website.
AssistantCopy response Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider anthropic
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Added to archive Nov 21, 2026
ID 01m7y9m6r8y9mgtwn24y2e8j7rSource & license Imported from Frontier Reasoning Traces (source ). Imported records earn no Research Points.
Upstream record: train-1.parquet:8756
SultanR/frontier-reasoning-traces-sft, revision 0e6b23142b95f5fe.
License: Apache-2.0
Dataset releases Not yet included in a published release.
The user wants me to create a Python script that can scrape news articles from a website and then summarize them. This is a common task that involves:
Web scraping - using libraries like requests, BeautifulSoup, or newspaper3k
Text summarization - using either extractive or abstractive methods
Let me create a comprehensive solution that includes:
A news scraper class that can handle different websites
Multiple summarization methods (extractive and AI-based)
Error handling and rate limiting
Different approaches for different use cases
I'll structure it as follows:
Basic implementation using newspaper3k (easiest approach)
Custom implementation using BeautifulSoup
Summarization using different methods:
Extractive summarization (using sumy or custom)
Using transformers/huggingface models
Using OpenAI API (optional)
Let me write clean, well-documented code with proper error handling. # News Article Scraper and Summarizer
Here's a comprehensive Python solution for scraping and summarizing news articles.
Project Structure
code Copy code
news_scraper/
├── scraper.py # Main scraper module
├── summarizer.py # Summarization methods
├── main.py # Entry point
├── requirements.txt # Dependencies
└── config.py # Configuration
1. Requirements
text Copy code
# requirements.txt
requests>=2.31.0
beautifulsoup4>=4.12.0
newspaper3k>=0.2.8
lxml>=4.9.0
nltk>=3.8.0
sumy>=0.11.0
transformers>=4.30.0
torch>=2.0.0
feedparser>=6.0.0
fake-useragent>=1.1.0
2. Configuration
python Copy code
# config.py
"""Configuration settings for the news scraper."""
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class ScraperConfig:
"""Configuration for web scraping."""
# Request settings
timeout: int = 10
max_retries: int = 3
delay_between_requests: float = 1.0
# User agent rotation
rotate_user_agent: bool = True
# Parsing settings
min_article_length: int = 100
max_articles: int = 10
# Headers
default_headers: dict = field(default_factory=lambda: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
})
@dataclass
class SummarizerConfig:
"""Configuration for text summarization."""
# Summary settings
summary_sentences: int = 3
summary_ratio: float = 0.3
# Model settings
model_name: str = "facebook/bart-large-cnn"
max_input_length: int = 1024
max_summary_length: int = 150
min_summary_length: int = 30
# Method: 'extractive', 'abstractive', or 'hybrid'
method: str = "extractive"
# Predefined news sources with their RSS feeds
NEWS_SOURCES = {
'bbc': {
'name': 'BBC News',
'rss': 'http://feeds.bbci.co.uk/news/rss.xml',
'base_url': 'https://www.bbc.com'
},
'cnn': {
'name': 'CNN',
'rss': 'http://rss.cnn.com/rss/edition.rss',
'base_url': 'https://www.cnn.com'
},
'reuters': {
'name': 'Reuters',
'rss': 'https://www.reutersagency.com/feed/',
'base_url': 'https://www.reuters.com'
},
'techcrunch': {
'name': 'TechCrunch',
'rss': 'https://techcrunch.com/feed/',
'base_url': 'https://techcrunch.com'
},
'hackernews': {
'name': 'Hacker News',
'rss': 'https://hnrss.org/frontpage',
'base_url': 'https://news.ycombinator.com'
}
}
3. Scraper Module
4. Summarizer Module
5. Main Application
6. Usage Examples
Quick Start
bash Copy code
# Install dependencies
pip install -r requirements.txt
# Run from command line
python main.py --source bbc --max 5 --method extractive
# Or use as library
python -c "
from scraper import NewsScraper
from summarizer import NewsSummarizer
scraper = NewsScraper()
summarizer = NewsSummarizer()
articles = scraper.scrape_source('bbc', max_articles=3)
for article in summarizer.summarize_articles(articles):
print(f'{article.title}')
print(f'Summary: {article.summary}\n')
"
This implementation includes:
Multiple scraping methods - BeautifulSoup and newspaper3k
RSS feed support - Parse any RSS/Atom feed
Multiple summarization algorithms - Extractive, TextRank, LSA, Transformer-based
Configurable settings - Timeouts, rate limiting, summary length
Error handling - Graceful fallbacks and logging
Export options - JSON, CSV, text output
CLI interface - Easy command-line usage
Show full message · 1,456 lines # scraper.py
"""
News article scraper supporting multiple methods:
- Direct URL scraping
- RSS feed parsing
- newspaper3k library
"""
import time
import logging
from typing import List, Optional, Dict, Any
from dataclasses import dataclass, field
from datetime import datetime
from abc import ABC, abstractmethod
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup
import feedparser
try:
from newspaper import Article, Config as NewspaperConfig
NEWSPAPER_AVAILABLE = True
except ImportError:
NEWSPAPER_AVAILABLE = False
try:
from fake_useragent import UserAgent
UA_AVAILABLE = True
except ImportError:
UA_AVAILABLE = False
from config import ScraperConfig, NEWS_SOURCES
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class NewsArticle:
"""Data class representing a news article."""
url: str
title: str = ""
text: str = ""
authors: List[str] = field(default_factory=list)
publish_date: Optional[datetime] = None
source: str = ""
summary: str = ""
keywords: List[str] = field(default_factory=list)
image_url: Optional[str] = None
scraped_at: datetime = field(default_factory=datetime.now)
def to_dict(self) -> Dict[str, Any]:
"""Convert article to dictionary."""
return {
'url': self.url,
'title': self.title,
'text': self.text,
'authors': self.authors,
'publish_date': self.publish_date.isoformat() if self.publish_date else None,
'source': self.source,
'summary': self.summary,
'keywords': self.keywords,
'image_url': self.image_url,
'scraped_at': self.scraped_at.isoformat()
}
def __str__(self) -> str:
return f"Article: {self.title[:50]}..." if len(self.title) > 50 else f"Article: {self.title}"
class BaseScraper(ABC):
"""Abstract base class for news scrapers."""
def __init__(self, config: Optional[ScraperConfig] = None):
self.config = config or ScraperConfig()
self.session = self._create_session()
self._user_agent = UserAgent() if UA_AVAILABLE and self.config.rotate_user_agent else None
def _create_session(self) -> requests.Session:
"""Create a requests session with retry logic."""
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=requests.adapters.Retry(
total=self.config.max_retries,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504]
)
)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def _get_headers(self) -> dict:
"""Get request headers with optional user agent rotation."""
headers = self.config.default_headers.copy()
if self._user_agent:
headers['User-Agent'] = self._user_agent.random
else:
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
return headers
def _fetch_page(self, url: str) -> Optional[str]:
"""Fetch a web page with error handling."""
try:
response = self.session.get(
url,
headers=self._get_headers(),
timeout=self.config.timeout
)
response.raise_for_status()
return response.text
except requests.RequestException as e:
logger.error(f"Failed to fetch {url}: {e}")
return None
@abstractmethod
def scrape_article(self, url: str) -> Optional[NewsArticle]:
"""Scrape a single article from URL."""
pass
@abstractmethod
def scrape_source(self, source: str, max_articles: int = 10) -> List[NewsArticle]:
"""Scrape multiple articles from a news source."""
pass
class BeautifulSoupScraper(BaseScraper):
"""Scraper using BeautifulSoup for custom parsing."""
# Common CSS selectors for article content
CONTENT_SELECTORS = [
'article',
'[class*="article-body"]',
'[class*="article-content"]',
'[class*="story-body"]',
'[class*="post-content"]',
'[itemprop="articleBody"]',
'.entry-content',
'.content-body',
'main'
]
TITLE_SELECTORS = [
'h1',
'[class*="headline"]',
'[class*="title"]',
'[itemprop="headline"]'
]
def scrape_article(self, url: str) -> Optional[NewsArticle]:
"""Scrape article using BeautifulSoup."""
html = self._fetch_page(url)
if not html:
return None
soup = BeautifulSoup(html, 'lxml')
article = NewsArticle(url=url)
# Extract title
article.title = self._extract_title(soup)
# Extract main content
article.text = self._extract_content(soup)
# Extract metadata
article.authors = self._extract_authors(soup)
article.publish_date = self._extract_date(soup)
article.image_url = self._extract_image(soup)
article.source = urlparse(url).netloc
# Validate article
if len(article.text) < self.config.min_article_length:
logger.warning(f"Article too short: {url}")
return None
return article
def _extract_title(self, soup: BeautifulSoup) -> str:
"""Extract article title."""
# Try Open Graph title first
og_title = soup.find('meta', property='og:title')
if og_title and og_title.get('content'):
return og_title['content'].strip()
# Try common title selectors
for selector in self.TITLE_SELECTORS:
element = soup.select_one(selector)
if element:
return element.get_text(strip=True)
# Fallback to page title
title_tag = soup.find('title')
return title_tag.get_text(strip=True) if title_tag else ""
def _extract_content(self, soup: BeautifulSoup) -> str:
"""Extract main article content."""
# Remove unwanted elements
for tag in soup.find_all(['script', 'style', 'nav', 'header', 'footer', 'aside', 'advertisement']):
tag.decompose()
# Try content selectors
for selector in self.CONTENT_SELECTORS:
content = soup.select_one(selector)
if content:
paragraphs = content.find_all('p')
text = ' '.join(p.get_text(strip=True) for p in paragraphs)
if len(text) > self.config.min_article_length:
return text
# Fallback: get all paragraphs
paragraphs = soup.find_all('p')
return ' '.join(p.get_text(strip=True) for p in paragraphs if len(p.get_text(strip=True)) > 20)
def _extract_authors(self, soup: BeautifulSoup) -> List[str]:
"""Extract article authors."""
authors = []
# Try schema.org markup
author_elements = soup.find_all(itemprop='author')
for elem in author_elements:
name = elem.find(itemprop='name')
if name:
authors.append(name.get_text(strip=True))
elif elem.get_text(strip=True):
authors.append(elem.get_text(strip=True))
# Try meta tags
if not authors:
author_meta = soup.find('meta', attrs={'name': 'author'})
if author_meta and author_meta.get('content'):
authors.append(author_meta['content'])
return authors
def _extract_date(self, soup: BeautifulSoup) -> Optional[datetime]:
"""Extract publication date."""
from dateutil import parser as date_parser
# Try common date attributes
date_selectors = [
('meta', {'property': 'article:published_time'}),
('meta', {'name': 'publication_date'}),
('time', {'datetime': True}),
]
for tag, attrs in date_selectors:
element = soup.find(tag, attrs)
if element:
date_str = element.get('content') or element.get('datetime')
if date_str:
try:
return date_parser.parse(date_str)
except:
pass
return None
def _extract_image(self, soup: BeautifulSoup) -> Optional[str]:
"""Extract main article image."""
og_image = soup.find('meta', property='og:image')
if og_image and og_image.get('content'):
return og_image['content']
return None
def scrape_source(self, source: str, max_articles: int = 10) -> List[NewsArticle]:
"""Scrape articles from a news source using RSS feed."""
if source not in NEWS_SOURCES:
logger.error(f"Unknown source: {source}")
return []
source_info = NEWS_SOURCES[source]
rss_url = source_info['rss']
# Parse RSS feed
feed = feedparser.parse(rss_url)
articles = []
for entry in feed.entries[:max_articles]:
url = entry.get('link')
if not url:
continue
logger.info(f"Scraping: {url}")
article = self.scrape_article(url)
if article:
# Override with RSS metadata if available
if not article.title and entry.get('title'):
article.title = entry['title']
if entry.get('published_parsed'):
article.publish_date = datetime(*entry.published_parsed[:6])
article.source = source_info['name']
articles.append(article)
# Rate limiting
time.sleep(self.config.delay_between_requests)
return articles
class Newspaper3kScraper(BaseScraper):
"""Scraper using newspaper3k library for robust article extraction."""
def __init__(self, config: Optional[ScraperConfig] = None):
super().__init__(config)
if not NEWSPAPER_AVAILABLE:
raise ImportError("newspaper3k is not installed. Run: pip install newspaper3k")
self.newspaper_config = NewspaperConfig()
self.newspaper_config.browser_user_agent = self._get_headers()['User-Agent']
self.newspaper_config.request_timeout = self.config.timeout
def scrape_article(self, url: str) -> Optional[NewsArticle]:
"""Scrape article using newspaper3k."""
try:
article = Article(url, config=self.newspaper_config)
article.download()
article.parse()
# Try NLP analysis for keywords
try:
article.nlp()
keywords = article.keywords
summary = article.summary
except:
keywords = []
summary = ""
news_article = NewsArticle(
url=url,
title=article.title,
text=article.text,
authors=article.authors,
publish_date=article.publish_date,
source=urlparse(url).netloc,
keywords=keywords,
image_url=article.top_image,
summary=summary
)
if len(news_article.text) < self.config.min_article_length:
logger.warning(f"Article too short: {url}")
return None
return news_article
except Exception as e:
logger.error(f"Failed to scrape {url}: {e}")
return None
def scrape_source(self, source: str, max_articles: int = 10) -> List[NewsArticle]:
"""Scrape articles from a news source."""
if source not in NEWS_SOURCES:
logger.error(f"Unknown source: {source}")
return []
source_info = NEWS_SOURCES[source]
feed = feedparser.parse(source_info['rss'])
articles = []
for entry in feed.entries[:max_articles]:
url = entry.get('link')
if not url:
continue
logger.info(f"Scraping: {url}")
article = self.scrape_article(url)
if article:
article.source = source_info['name']
articles.append(article)
time.sleep(self.config.delay_between_requests)
return articles
class NewsScraper:
"""
Unified news scraper with automatic method selection.
"""
def __init__(self, config: Optional[ScraperConfig] = None, method: str = 'auto'):
self.config = config or ScraperConfig()
self.method = method
self._scraper = self._get_scraper()
def _get_scraper(self) -> BaseScraper:
"""Get appropriate scraper based on method."""
if self.method == 'newspaper' or (self.method == 'auto' and NEWSPAPER_AVAILABLE):
try:
return Newspaper3kScraper(self.config)
except ImportError:
pass
return BeautifulSoupScraper(self.config)
def scrape_url(self, url: str) -> Optional[NewsArticle]:
"""Scrape a single URL."""
return self._scraper.scrape_article(url)
def scrape_urls(self, urls: List[str]) -> List[NewsArticle]:
"""Scrape multiple URLs."""
articles = []
for url in urls:
article = self.scrape_url(url)
if article:
articles.append(article)
time.sleep(self.config.delay_between_requests)
return articles
def scrape_source(self, source: str, max_articles: int = None) -> List[NewsArticle]:
"""Scrape articles from a predefined news source."""
max_articles = max_articles or self.config.max_articles
return self._scraper.scrape_source(source, max_articles)
def scrape_rss(self, rss_url: str, max_articles: int = None) -> List[NewsArticle]:
"""Scrape articles from a custom RSS feed."""
max_articles = max_articles or self.config.max_articles
feed = feedparser.parse(rss_url)
urls = [entry.get('link') for entry in feed.entries[:max_articles] if entry.get('link')]
return self.scrape_urls(urls)
@staticmethod
def list_sources() -> List[str]:
"""List available news sources."""
return list(NEWS_SOURCES.keys())
# summarizer.py
"""
Text summarization module supporting multiple methods:
- Extractive summarization (sentence scoring)
- Abstractive summarization (transformer models)
"""
import logging
from typing import List, Optional, Union
from abc import ABC, abstractmethod
import re
from collections import Counter
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from config import SummarizerConfig
from scraper import NewsArticle
logger = logging.getLogger(__name__)
# Download required NLTK data
def download_nltk_data():
"""Download required NLTK datasets."""
datasets = ['punkt', 'stopwords', 'averaged_perceptron_tagger']
for dataset in datasets:
try:
nltk.data.find(f'tokenizers/{dataset}')
except LookupError:
nltk.download(dataset, quiet=True)
download_nltk_data()
class BaseSummarizer(ABC):
"""Abstract base class for summarizers."""
def __init__(self, config: Optional[SummarizerConfig] = None):
self.config = config or SummarizerConfig()
@abstractmethod
def summarize(self, text: str) -> str:
"""Generate summary from text."""
pass
def summarize_article(self, article: NewsArticle) -> NewsArticle:
"""Summarize a news article."""
if article.text:
article.summary = self.summarize(article.text)
return article
def summarize_articles(self, articles: List[NewsArticle]) -> List[NewsArticle]:
"""Summarize multiple articles."""
return [self.summarize_article(article) for article in articles]
class ExtractiveSummarizer(BaseSummarizer):
"""
Extractive summarization using sentence scoring.
Selects the most important sentences from the original text.
"""
def __init__(self, config: Optional[SummarizerConfig] = None):
super().__init__(config)
self.stop_words = set(stopwords.words('english'))
def summarize(self, text: str, num_sentences: int = None) -> str:
"""Generate extractive summary."""
num_sentences = num_sentences or self.config.summary_sentences
# Tokenize into sentences
sentences = sent_tokenize(text)
if len(sentences) <= num_sentences:
return text
# Score sentences
scores = self._score_sentences(sentences)
# Select top sentences while maintaining order
ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
top_indices = sorted([idx for idx, _ in ranked[:num_sentences]])
summary = ' '.join(sentences[i] for i in top_indices)
return summary
def _score_sentences(self, sentences: List[str]) -> List[float]:
"""Score sentences based on multiple features."""
# Get word frequencies
all_words = []
for sentence in sentences:
words = word_tokenize(sentence.lower())
words = [w for w in words if w.isalnum() and w not in self.stop_words]
all_words.extend(words)
word_freq = Counter(all_words)
max_freq = max(word_freq.values()) if word_freq else 1
# Normalize frequencies
for word in word_freq:
word_freq[word] /= max_freq
# Score each sentence
scores = []
for i, sentence in enumerate(sentences):
words = word_tokenize(sentence.lower())
words = [w for w in words if w.isalnum() and w not in self.stop_words]
# Word frequency score
freq_score = sum(word_freq.get(w, 0) for w in words) / max(len(words), 1)
# Position score (earlier sentences are more important)
position_score = 1 / (i + 1)
# Length score (prefer medium-length sentences)
length_score = min(len(words) / 20, 1) if len(words) < 40 else 0.5
# Title word bonus (if first sentence contains title-like words)
title_bonus = 0.2 if i == 0 else 0
# Combined score
total_score = (
freq_score * 0.5 +
position_score * 0.25 +
length_score * 0.15 +
title_bonus * 0.1
)
scores.append(total_score)
return scores
class TextRankSummarizer(BaseSummarizer):
"""
TextRank algorithm for extractive summarization.
Uses graph-based ranking similar to PageRank.
"""
def __init__(self, config: Optional[SummarizerConfig] = None):
super().__init__(config)
self.stop_words = set(stopwords.words('english'))
self.damping = 0.85
self.iterations = 50
self.convergence_threshold = 0.0001
def summarize(self, text: str, num_sentences: int = None) -> str:
"""Generate summary using TextRank."""
num_sentences = num_sentences or self.config.summary_sentences
sentences = sent_tokenize(text)
if len(sentences) <= num_sentences:
return text
# Build similarity matrix
similarity_matrix = self._build_similarity_matrix(sentences)
# Run TextRank
scores = self._textrank(similarity_matrix)
# Select top sentences
ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
top_indices = sorted([idx for idx, _ in ranked[:num_sentences]])
return ' '.join(sentences[i] for i in top_indices)
def _get_sentence_tokens(self, sentence: str) -> set:
"""Tokenize and clean sentence."""
words = word_tokenize(sentence.lower())
return set(w for w in words if w.isalnum() and w not in self.stop_words)
def _sentence_similarity(self, s1: str, s2: str) -> float:
"""Calculate similarity between two sentences."""
tokens1 = self._get_sentence_tokens(s1)
tokens2 = self._get_sentence_tokens(s2)
if not tokens1 or not tokens2:
return 0.0
# Jaccard similarity
intersection = tokens1 & tokens2
union = tokens1 | tokens2
return len(intersection) / len(union)
def _build_similarity_matrix(self, sentences: List[str]) -> List[List[float]]:
"""Build sentence similarity matrix."""
n = len(sentences)
matrix = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i != j:
matrix[i][j] = self._sentence_similarity(sentences[i], sentences[j])
# Normalize rows
for i in range(n):
row_sum = sum(matrix[i])
if row_sum > 0:
matrix[i] = [x / row_sum for x in matrix[i]]
return matrix
def _textrank(self, matrix: List[List[float]]) -> List[float]:
"""Run TextRank algorithm."""
n = len(matrix)
scores = [1.0 / n] * n
for _ in range(self.iterations):
new_scores = []
for i in range(n):
score = (1 - self.damping) / n
for j in range(n):
if matrix[j][i] > 0:
score += self.damping * scores[j] * matrix[j][i]
new_scores.append(score)
# Check convergence
diff = sum(abs(new_scores[i] - scores[i]) for i in range(n))
scores = new_scores
if diff < self.convergence_threshold:
break
return scores
class TransformerSummarizer(BaseSummarizer):
"""
Abstractive summarization using transformer models.
Uses Hugging Face transformers library.
"""
def __init__(self, config: Optional[SummarizerConfig] = None):
super().__init__(config)
self._pipeline = None
@property
def pipeline(self):
"""Lazy load the summarization pipeline."""
if self._pipeline is None:
try:
from transformers import pipeline
logger.info(f"Loading model: {self.config.model_name}")
self._pipeline = pipeline(
"summarization",
model=self.config.model_name,
tokenizer=self.config.model_name
)
except ImportError:
raise ImportError("transformers library not installed. Run: pip install transformers torch")
return self._pipeline
def summarize(self, text: str) -> str:
"""Generate abstractive summary using transformer model."""
# Truncate input if necessary
if len(text) > self.config.max_input_length * 4: # Rough character estimate
text = text[:self.config.max_input_length * 4]
try:
result = self.pipeline(
text,
max_length=self.config.max_summary_length,
min_length=self.config.min_summary_length,
do_sample=False
)
return result[0]['summary_text']
except Exception as e:
logger.error(f"Summarization failed: {e}")
# Fallback to extractive
fallback = ExtractiveSummarizer(self.config)
return fallback.summarize(text)
class SumyWrapper(BaseSummarizer):
"""
Wrapper for sumy library summarizers.
Supports LSA, Luhn, LexRank, TextRank algorithms.
"""
ALGORITHMS = ['lsa', 'luhn', 'lexrank', 'textrank', 'edmundson']
def __init__(self, config: Optional[SummarizerConfig] = None, algorithm: str = 'lsa'):
super().__init__(config)
self.algorithm = algorithm.lower()
self._summarizer = None
self._parser = None
self._stemmer = None
def _load_sumy(self):
"""Load sumy components."""
if self._summarizer is not None:
return
try:
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.nlp.stemmers import Stemmer
from sumy.utils import get_stop_words
# Select algorithm
if self.algorithm == 'lsa':
from sumy.summarizers.lsa import LsaSummarizer as Summarizer
elif self.algorithm == 'luhn':
from sumy.summarizers.luhn import LuhnSummarizer as Summarizer
elif self.algorithm == 'lexrank':
from sumy.summarizers.lex_rank import LexRankSummarizer as Summarizer
elif self.algorithm == 'textrank':
from sumy.summarizers.text_rank import TextRankSummarizer as Summarizer
elif self.algorithm == 'edmundson':
from sumy.summarizers.edmundson import EdmundsonSummarizer as Summarizer
else:
raise ValueError(f"Unknown algorithm: {self.algorithm}")
self._stemmer = Stemmer('english')
self._summarizer = Summarizer(self._stemmer)
self._summarizer.stop_words = get_stop_words('english')
self._parser_class = PlaintextParser
self._tokenizer_class = Tokenizer
except ImportError:
raise ImportError("sumy library not installed. Run: pip install sumy")
def summarize(self, text: str, num_sentences: int = None) -> str:
"""Generate summary using sumy."""
self._load_sumy()
num_sentences = num_sentences or self.config.summary_sentences
parser = self._parser_class.from_string(text, self._tokenizer_class('english'))
summary_sentences = self._summarizer(parser.document, num_sentences)
return ' '.join(str(sentence) for sentence in summary_sentences)
class HybridSummarizer(BaseSummarizer):
"""
Hybrid summarizer combining extractive and abstractive methods.
First extracts key sentences, then refines with abstractive model.
"""
def __init__(self, config: Optional[SummarizerConfig] = None):
super().__init__(config)
self.extractive = TextRankSummarizer(config)
self._abstractive = None
@property
def abstractive(self):
"""Lazy load abstractive summarizer."""
if self._abstractive is None:
self._abstractive = TransformerSummarizer(self.config)
return self._abstractive
def summarize(self, text: str) -> str:
"""Generate hybrid summary."""
# First pass: extractive
extracted = self.extractive.summarize(text, num_sentences=5)
# Second pass: abstractive refinement
try:
summary = self.abstractive.summarize(extracted)
return summary
except Exception as e:
logger.warning(f"Abstractive pass failed: {e}")
return extracted
class NewsSummarizer:
"""
Unified news summarizer with multiple method support.
"""
METHODS = {
'extractive': ExtractiveSummarizer,
'textrank': TextRankSummarizer,
'transformer': TransformerSummarizer,
'hybrid': HybridSummarizer,
'lsa': lambda cfg: SumyWrapper(cfg, 'lsa'),
'lexrank': lambda cfg: SumyWrapper(cfg, 'lexrank'),
}
def __init__(self, config: Optional[SummarizerConfig] = None, method: str = 'extractive'):
self.config = config or SummarizerConfig()
self.method = method
self._summarizer = self._get_summarizer()
def _get_summarizer(self) -> BaseSummarizer:
"""Get summarizer based on method."""
if self.method not in self.METHODS:
raise ValueError(f"Unknown method: {self.method}. Available: {list(self.METHODS.keys())}")
creator = self.METHODS[self.method]
if callable(creator) and not isinstance(creator, type):
return creator(self.config)
return creator(self.config)
def summarize(self, text: str) -> str:
"""Summarize text."""
return self._summarizer.summarize(text)
def summarize_article(self, article: NewsArticle) -> NewsArticle:
"""Summarize a news article."""
return self._summarizer.summarize_article(article)
def summarize_articles(self, articles: List[NewsArticle]) -> List[NewsArticle]:
"""Summarize multiple articles."""
return self._summarizer.summarize_articles(articles)
@classmethod
def available_methods(cls) -> List[str]:
"""List available summarization methods."""
return list(cls.METHODS.keys())
# main.py
"""
Main application for news scraping and summarization.
"""
import argparse
import json
import sys
from typing import List, Optional
from datetime import datetime
from config import ScraperConfig, SummarizerConfig, NEWS_SOURCES
from scraper import NewsScraper, NewsArticle
from summarizer import NewsSummarizer
def scrape_and_summarize(
source: Optional[str] = None,
urls: Optional[List[str]] = None,
rss_url: Optional[str] = None,
max_articles: int = 5,
summarization_method: str = 'extractive',
summary_sentences: int = 3,
output_format: str = 'text'
) -> List[NewsArticle]:
"""
Main function to scrape and summarize news articles.
Args:
source: Predefined news source (bbc, cnn, etc.)
urls: List of specific URLs to scrape
rss_url: Custom RSS feed URL
max_articles: Maximum number of articles to scrape
summarization_method: Method for summarization
summary_sentences: Number of sentences in summary
output_format: Output format (text, json)
Returns:
List of NewsArticle objects with summaries
"""
# Configure scraper
scraper_config = ScraperConfig(max_articles=max_articles)
scraper = NewsScraper(config=scraper_config)
# Configure summarizer
summarizer_config = SummarizerConfig(
summary_sentences=summary_sentences,
method=summarization_method
)
summarizer = NewsSummarizer(
config=summarizer_config,
method=summarization_method
)
# Scrape articles
articles = []
if urls:
print(f"📥 Scraping {len(urls)} URLs...")
articles = scraper.scrape_urls(urls)
elif source:
print(f"📥 Scraping from {source}...")
articles = scraper.scrape_source(source, max_articles)
elif rss_url:
print(f"📥 Scraping RSS feed: {rss_url}")
articles = scraper.scrape_rss(rss_url, max_articles)
else:
print("❌ No source specified!")
return []
print(f"✅ Scraped {len(articles)} articles")
# Summarize articles
print(f"📝 Summarizing using {summarization_method} method...")
articles = summarizer.summarize_articles(articles)
print("✅ Summarization complete!")
return articles
def format_output(articles: List[NewsArticle], format_type: str = 'text') -> str:
"""Format articles for output."""
if format_type == 'json':
return json.dumps([a.to_dict() for a in articles], indent=2, default=str)
# Text format
output = []
output.append("=" * 80)
output.append(f"📰 NEWS SUMMARY REPORT - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
output.append("=" * 80)
for i, article in enumerate(articles, 1):
output.append(f"\n{'─' * 80}")
output.append(f"📌 Article {i}: {article.title}")
output.append(f"🔗 URL: {article.url}")
output.append(f"📅 Date: {article.publish_date or 'Unknown'}")
output.append(f"✍️ Authors: {', '.join(article.authors) if article.authors else 'Unknown'}")
output.append(f"📰 Source: {article.source}")
output.append(f"\n📋 SUMMARY:")
output.append(f" {article.summary}")
output.append(f"\n📊 Original length: {len(article.text)} chars | Summary: {len(article.summary)} chars")
output.append(f"\n{'=' * 80}")
output.append(f"Total articles processed: {len(articles)}")
output.append("=" * 80)
return '\n'.join(output)
def main():
"""CLI entry point."""
parser = argparse.ArgumentParser(
description='Scrape and summarize news articles',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Scrape from BBC
python main.py --source bbc --max 5
# Scrape specific URLs
python main.py --urls "https://example.com/article1" "https://example.com/article2"
# Use transformer model for summarization
python main.py --source cnn --method transformer
# Output as JSON
python main.py --source bbc --format json > news.json
Available sources: """ + ', '.join(NEWS_SOURCES.keys())
)
# Source arguments
source_group = parser.add_mutually_exclusive_group()
source_group.add_argument(
'--source', '-s',
choices=list(NEWS_SOURCES.keys()),
help='Predefined news source to scrape'
)
source_group.add_argument(
'--urls', '-u',
nargs='+',
help='Specific URLs to scrape'
)
source_group.add_argument(
'--rss',
help='Custom RSS feed URL'
)
# Options
parser.add_argument(
'--max', '-m',
type=int,
default=5,
help='Maximum number of articles (default: 5)'
)
parser.add_argument(
'--method',
choices=NewsSummarizer.available_methods(),
default='extractive',
help='Summarization method (default: extractive)'
)
parser.add_argument(
'--sentences',
type=int,
default=3,
help='Number of sentences in summary (default: 3)'
)
parser.add_argument(
'--format', '-f',
choices=['text', 'json'],
default='text',
help='Output format (default: text)'
)
parser.add_argument(
'--output', '-o',
help='Output file (default: stdout)'
)
parser.add_argument(
'--list-sources',
action='store_true',
help='List available news sources'
)
args = parser.parse_args()
# List sources
if args.list_sources:
print("Available news sources:")
for key, info in NEWS_SOURCES.items():
print(f" {key:12} - {info['name']}")
sys.exit(0)
# Check if source specified
if not args.source and not args.urls and not args.rss:
parser.print_help()
print("\n❌ Error: Please specify a source (--source), URLs (--urls), or RSS feed (--rss)")
sys.exit(1)
# Run scraper
try:
articles = scrape_and_summarize(
source=args.source,
urls=args.urls,
rss_url=args.rss,
max_articles=args.max,
summarization_method=args.method,
summary_sentences=args.sentences,
output_format=args.format
)
# Format output
output = format_output(articles, args.format)
# Write output
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(output)
print(f"✅ Output written to {args.output}")
else:
print(output)
except KeyboardInterrupt:
print("\n⚠️ Interrupted by user")
sys.exit(130)
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)
if __name__ == '__main__':
main()
# examples.py
"""
Usage examples for the news scraper and summarizer.
"""
from scraper import NewsScraper, NewsArticle
from summarizer import NewsSummarizer, ExtractiveSummarizer, TextRankSummarizer
from config import ScraperConfig, SummarizerConfig
def example_basic_usage():
"""Basic usage example."""
print("\n" + "="*50)
print("Example 1: Basic Usage")
print("="*50)
# Initialize scraper and summarizer
scraper = NewsScraper()
summarizer = NewsSummarizer(method='extractive')
# Scrape a single URL
url = "https://www.bbc.com/news/technology"
article = scraper.scrape_url(url)
if article:
# Summarize the article
article = summarizer.summarize_article(article)
print(f"Title: {article.title}")
print(f"Source: {article.source}")
print(f"\nSummary:\n{article.summary}")
def example_multiple_sources():
"""Scraping from multiple sources."""
print("\n" + "="*50)
print("Example 2: Multiple Sources")
print("="*50)
scraper = NewsScraper()
summarizer = NewsSummarizer(method='textrank')
# List available sources
print("Available sources:", scraper.list_sources())
# Scrape from BBC
articles = scraper.scrape_source('bbc', max_articles=3)
articles = summarizer.summarize_articles(articles)
for article in articles:
print(f"\n📰 {article.title}")
print(f" Summary: {article.summary[:200]}...")
def example_custom_config():
"""Using custom configuration."""
print("\n" + "="*50)
print("Example 3: Custom Configuration")
print("="*50)
# Custom scraper config
scraper_config = ScraperConfig(
timeout=15,
max_retries=5,
delay_between_requests=2.0,
min_article_length=200
)
# Custom summarizer config
summarizer_config = SummarizerConfig(
summary_sentences=5,
summary_ratio=0.4
)
scraper = NewsScraper(config=scraper_config)
summarizer = NewsSummarizer(config=summarizer_config, method='lexrank')
articles = scraper.scrape_source('techcrunch', max_articles=2)
articles = summarizer.summarize_articles(articles)
for article in articles:
print(f"\n📰 {article.title}")
print(f" {article.summary}")
def example_different_summarizers():
"""Compare different summarization methods."""
print("\n" + "="*50)
print("Example 4: Comparing Summarizers")
print("="*50)
# Sample text
text = """
Artificial intelligence has transformed numerous industries over the past decade.
Machine learning algorithms now power recommendation systems, autonomous vehicles,
and medical diagnostics. The technology continues to evolve rapidly, with new
breakthroughs in natural language processing and computer vision. Companies are
investing billions in AI research and development. Experts predict that AI will
create significant economic value while also posing challenges related to job
displacement and ethical considerations. Governments worldwide are developing
regulations to ensure responsible AI development. The future of AI looks promising,
with applications extending to climate change mitigation, drug discovery, and
personalized education. However, concerns about bias in AI systems and data privacy
remain important topics of discussion.
"""
methods = ['extractive', 'textrank', 'lsa', 'lexrank']
for method in methods:
try:
summarizer = NewsSummarizer(method=method)
summary = summarizer.summarize(text)
print(f"\n{method.upper()}:")
print(f" {summary}")
except Exception as e:
print(f"\n{method.upper()}: Error - {e}")
def example_rss_feed():
"""Scraping from custom RSS feed."""
print("\n" + "="*50)
print("Example 5: Custom RSS Feed")
print("="*50)
scraper = NewsScraper()
summarizer = NewsSummarizer()
# Scrape from Hacker News RSS
rss_url = "https://hnrss.org/frontpage"
articles = scraper.scrape_rss(rss_url, max_articles=3)
if articles:
articles = summarizer.summarize_articles(articles)
for article in articles:
print(f"\n📰 {article.title}")
print(f"🔗 {article.url}")
print(f"📝 {article.summary[:150]}...")
def example_batch_processing():
"""Batch processing multiple URLs."""
print("\n" + "="*50)
print("Example 6: Batch Processing")
print("="*50)
urls = [
"https://example.com/article1",
"https://example.com/article2",
"https://example.com/article3"
]
scraper = NewsScraper()
summarizer = NewsSummarizer()
# Process in batches
articles = scraper.scrape_urls(urls)
articles = summarizer.summarize_articles(articles)
print(f"Processed {len(articles)} articles")
def example_export_results():
"""Export results to different formats."""
print("\n" + "="*50)
print("Example 7: Export Results")
print("="*50)
import json
import csv
scraper = NewsScraper()
summarizer = NewsSummarizer()
articles = scraper.scrape_source('bbc', max_articles=3)
articles = summarizer.summarize_articles(articles)
# Export to JSON
json_data = [article.to_dict() for article in articles]
with open('news_output.json', 'w') as f:
json.dump(json_data, f, indent=2, default=str)
print("Exported to news_output.json")
# Export to CSV
if articles:
with open('news_output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=articles[0].to_dict().keys())
writer.writeheader()
for article in articles:
writer.writerow(article.to_dict())
print("Exported to news_output.csv")
if __name__ == '__main__':
# Run examples
example_basic_usage()
example_different_summarizers()