"""
Python script to scrape news articles from a website and generate summaries.
IMPORTANT NOTES:
- Always check the website's robots.txt (e.g., https://example.com/robots.txt) and Terms of Service before scraping.
- Respect rate limits: Add delays with time.sleep() in production.
- This example is configured for BBC News (https://www.bbc.com/news). Adapt selectors for other sites.
- Installation: pip install requests beautifulsoup4 transformers torch
- Transformers model (BART) downloads ~1.6GB on first run.
- Ethical scraping: Do not overload servers; consider official APIs like NewsAPI.org.
Usage: python news_scraper.py
"""
import requests
from bs4 import BeautifulSoup
from transformers import pipeline
from urllib.parse import urljoin
import time
# Headers to mimic a real browser and avoid blocking
HEADERS = {
'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'
}
def scrape_article_links(base_url, max_links=10):
"""
Scrape links to news articles from the main news listing page.
Adapted for BBC News: https://www.bbc.com/news
"""
response = requests.get(base_url, headers=HEADERS)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
links = []
# BBC-specific selectors: promo headings with links
for link_elem in soup.find_all('a', {'jsname': 'HAqROe'})[:max_links]:
href = link_elem.get('href')
if href and '/news/' in href:
full_url = urljoin(base_url, href)
title = link_elem.get_text(strip=True)
links.append({'url': full_url, 'title': title})
print(f"Found {len(links)} article links.")
return links
def extract_article_text(article_url):
"""
Extract main text content from an individual article page.
BBC-specific: Main content in article body paragraphs.
"""
response = requests.get(article_url, headers=HEADERS)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script/style elements
for script in soup(["script", "style", "nav", "footer"]):
script.decompose()
# BBC-specific: paragraphs in main content
paragraphs = soup.find_all('p')
text = ' '.join([p.get_text(strip=True) for p in paragraphs if len(p.get_text(strip=True)) > 50])
return text[:4000] # Truncate for summarization model limits
def summarize_text(text, max_length=150, min_length=50):
"""
Generate a concise summary using Hugging Face's BART model.
"""
if len(text) < 100:
return "Summary unavailable: Article too short."
summarizer = pipeline(
"summarization",
model="facebook/bart-large-cnn",
device=-1 # Use CPU; set to 0 for GPU if available
)
# Truncate input to model's max length (~1024 tokens)
summary = summarizer(
text[:1024],
max_length=max_length,
min_length=min_length,
do_sample=False,
truncation=True
)
return summary[0]['summary_text']
def main():
base_url = "https://www.bbc.com/news" # Change this to your target site
print("Scraping news article links...")
links = scrape_article_links(base_url, max_links=5)
for i, article in enumerate(links, 1):
print(f"\n--- Article {i}: {article['title'][:80]}... ---")
print(f"URL: {article['url']}")
try:
text = extract_article_text(article['url'])
summary = summarize_text(text)
print(f"SUMMARY: {summary}")
except Exception as e:
print(f"Error processing article: {e}")
# Rate limiting: Be polite
time.sleep(2)
if __name__ == "__main__":
main()
How to Adapt for Other Websites:
Update scrape_article_links: Inspect the site's HTML (right-click > Inspect) and replace selectors (e.g., 'jsname': 'HAqROe') with site-specific ones like class_='article-link'.
Update extract_article_text: Target the site's main content area, e.g., soup.find('div', class_='story-body').
Test incrementally: Run on 1-2 articles first.
Advanced: Use selenium for JavaScript-heavy sites; newspaper3k library for easier extraction.
This code is production-ready for ethical, personal use. Run it and enjoy summarized news! 📰