#!/usr/bin/env python3
"""
Sherlock's News Scraper and Summarizer
======================================
This script uses the `newspaper3k` library to ethically scrape news articles from
a given news source URL (e.g., homepage or RSS feed) and generate summaries.
Key Features:
- Downloads and parses multiple articles from a news source.
- Extracts clean text, title, authors, date, and a summary.
- Handles errors gracefully.
- Configurable memoization to avoid re-downloading.
Ethical Notes:
- Always respect robots.txt and terms of service.
- Use sparingly to avoid overloading servers.
- Prefer RSS feeds or APIs (e.g., NewsAPI.org) for production use.
- newspaper3k respects rate limits.
Installation:
pip install newspaper3k
Usage:
python news_scraper.py "https://example-news-site.com"
or
python news_scraper.py "https://rss.example-news-site.com/feed.xml"
"""
import sys
import argparse
from newspaper import Article, Config, Source, ArticleException
from urllib.parse import urljoin, urlparse
def setup_config():
"""Setup newspaper3k config for better parsing and memoization."""
config = Config()
config.fetch_images = False # Faster, no images
config.memoize_articles = True # Cache parsed articles
config.request_timeout = 10
config.browser_user_agent = (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
)
return config
def scrape_and_summarize(source_url, max_articles=10, min_length=100):
"""
Scrape articles from source and summarize them.
Args:
source_url (str): News homepage or RSS feed URL.
max_articles (int): Max articles to process.
min_length (int): Min summary length to consider valid.
Returns:
list: List of dicts with article summaries.
"""
config = setup_config()
try:
source = Source(source_url, config=config)
source.build(min_threads=4, max_threads_per_source=4) # Parallel download
articles = []
processed = 0
print(f"Found {len(source.articles)} articles. Processing up to {max_articles}...")
for article_url in source.articles[:max_articles]:
try:
article = Article(article_url, config=config)
article.download()
article.parse()
article.nlp() # NLP for summary, keywords
# Filter short/irrelevant articles
if len(article.text) < 200:
continue
summary = {
'title': article.title,
'url': article.url,
'authors': article.authors,
'publish_date': article.publish_date,
'summary': article.summary if len(article.summary) >= min_length else "Summary too short.",
'keywords': article.keywords,
'top_image': article.top_image
}
articles.append(summary)
processed += 1
print(f"✓ Processed: {article.title[:60]}...")
except ArticleException as e:
print(f"✗ Failed to process {article_url}: {e}")
continue
print(f"\nSuccessfully processed {processed} articles.")
return articles
except Exception as e:
print(f"✗ Error building source from {source_url}: {e}")
return []
def print_summaries(articles, output_file=None):
"""Print or save summaries in a readable format."""
if not articles:
print("No articles to summarize.")
return
output = []
for i, art in enumerate(articles, 1):
output.append(f"\n{'='*80}")
output.append(f"Article {i}")
output.append(f"{'='*80}")
output.append(f"Title: {art['title']}")
output.append(f"URL: {art['url']}")
if art['authors']:
output.append(f"Authors: {', '.join(art['authors'])}")
if art['publish_date']:
output.append(f"Date: {art['publish_date']}")
output.append(f"\nSummary:\n{art['summary']}")
if art['keywords']:
output.append(f"\nKeywords: {', '.join(art['keywords'][:10])}") # Top 10
if art['top_image']:
output.append(f"Image: {art['top_image']}")
result = '\n'.join(output)
print(result)
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(result)
print(f"\nSaved to {output_file}")
def main():
parser = argparse.ArgumentParser(description="Scrape and summarize news articles.")
parser.add_argument("source_url", help="News source URL (homepage or RSS)")
parser.add_argument("-n", "--num-articles", type=int, default=10, help="Max articles to process (default: 10)")
parser.add_argument("-o", "--output", help="Output file (default: print to console)")
parser.add_argument("-l", "--min-length", type=int, default=100, help="Min summary length (default: 100)")
args = parser.parse_args()
if len(sys.argv) < 2:
parser.print_help()
print("\nExample: python news_scraper.py https://news.ycombinator.com")
sys.exit(1)
articles = scrape_and_summarize(args.source_url, args.num_articles, args.min_length)
print_summaries(articles, args.output)
if __name__ == "__main__":
main()
Quick Start Examples
-
BBC News (works well):
python news_scraper.py "https://www.bbc.com/news"
-
RSS Feed (faster, more reliable):
python news_scraper.py "https://feeds.bbci.co.uk/news/rss.xml"
-
Save to file:
python news_scraper.py "https://news.ycombinator.com" -n 5 -o summaries.txt
Tips & Troubleshooting
- Works best on: Major news sites (BBC, CNN, NYT, Hacker News).
- Rate limiting: If blocked, increase
request_timeout or use proxies.
- Customization: Extend
scrape_and_summarize for LLMs (e.g., integrate Hugging Face transformers for better summaries).
- Alternatives: For APIs, swap with
newsapi-python library.
- Legal: This is for personal/educational use. Check site ToS.
Built by Sherlock @ Trailblazer Labs. Elementary, my dear user! 🔍