The user wants a Python script to scrape news articles and summarize them.
This is a common task that involves two main parts:
- Scraping: Fetching the HTML of a webpage and extracting the main text content.
- Summarization: Processing the extracted text to generate a concise summary.
Tools and Libraries:
- Scraping:
requests: To make HTTP requests (get the webpage).
BeautifulSoup (from bs4): To parse the HTML and find specific tags.
- Summarization:
- Option A: Simple frequency-based summarization (NLTK or Spacy). This is old school and often produces poor results.
- Option B: Deep Learning models (Hugging Face Transformers). This is the modern standard but requires heavy dependencies (PyTorch/TensorFlow).
- Option C: OpenAI API. Easy, but costs money.
- Option D:
newspaper3k. This library actually does both scraping and NLP summarization out of the box. It's the most "all-in-one" solution for a beginner script.
- Option E:
sumy or gensim. Good middle ground for extractive summarization without massive model downloads.
Decision:
I should provide a solution that uses newspaper3k because it's specifically built for news articles and handles the messiness of parsing different news sites automatically. It also has built-in NLP summarization.
However, newspaper3k's built-in summarizer is basic. To provide a "better" (abstractive) summary, I should probably mention or implement a Hugging Face transformer pipeline as an alternative, but for a simple script, newspaper3k is the best starting point.
Let's stick to a custom script using requests + BeautifulSoup for specific scraping logic (to show how it works) and transformers (Hugging Face) for a high-quality summary. This demonstrates more control than just calling Article(url).download().
Wait, installing PyTorch is heavy. Let's offer two versions:
- The "Easy/Classic" way: Using
newspaper3k. It does everything in 5 lines.
- The "Robust/Modern" way: Using
requests + BeautifulSoup for scraping and a pre-trained Transformer model for summarization.
Actually, to keep it accessible, I will focus on newspaper3k first, as it's the most practical answer. I will also add a version using transformers for better quality, noting the hardware requirements.
Let's refine the plan:
- Prerequisites: Python installed.
- Libraries:
newspaper3k. It handles scraping, text extraction, and basic summarization.
- Code Structure:
- Import library.
- Define URL.
- Download and parse.
- Print title, text, and summary.
- Alternative (Better Summary): Mention
transformers pipeline.
Let's write the solution focusing on newspaper3k because it abstracts away the hardest part of scraping news: dealing with different HTML structures (CSS selectors) across CNN, BBC, Fox, etc.
Drafting the Code (newspaper3k approach):
from newspaper import Article
def scrape_and_summarize(url):
article = Article(url)
article.download()
article.parse()
article.nlp() # This runs the keyword extraction and summarization
return article.summary
This is too simple. The user might want to scrape multiple articles. I should add a list of URLs.
Drafting the Code (Hugging Face approach):
If the user wants a good summary, newspaper3k's NLP is often just extractive (picking top sentences). Abstractive summaries (like ChatGPT) are better.
I will provide a script that uses newspaper3k for the dirty work of getting the text, and then uses a Hugging Face model to summarize it. This makes the script actually useful.
Revised Plan:
- Installation:
pip install newspaper3k transformers torch
- Script:
- Use
newspaper3k to get clean text from a URL.
- Use
transformers (pipeline "summarization") to summarize that text.
- Explanation: Explain what each part does.
Potential Issues:
newspaper3k sometimes fails on paywalled sites or dynamic JS sites. I should mention this limitation.
- Transformers need to download models on first run.
Finalizing the Script Structure:
- Import libraries.
- Define a function
summarize_news(url).
- Inside: Initialize
Article, download/parse.
- Initialize Hugging Face summarizer.
- Run summarizer on
article.text.
- Print results.
This is a high-quality answer. It combines the best scraper library for news with the best summarization library.
Self-Correction:
Maybe the user doesn't want to download 500MB of PyTorch models.
I will provide two options:
- Option 1 (Lightweight): Uses
newspaper3k only. Fast, built-in NLP.
- Option 2 (High Quality): Uses
newspaper3k + transformers. Slower, requires GPU/CPU power, but produces human-like summaries.
This covers all bases.
Code for Option 1:
from newspaper import Article
url = "..."
article = Article(url)
article.download()
article.parse()
article.nlp()
print(article.summary)
Code for Option 2:
from newspaper import Article
from transformers import pipeline
summarizer = pipeline("summarization")
# ... get text ...
summary = summarizer(text, max_length=130, min_length=30)
I will present Option 2 as the main "Modern" solution but mention Option 1 as a fallback for speed.
Let's refine the prompt compliance. "Build a Python script..." implies a complete, runnable file.
I will add comments and error handling (e.g., try/except for HTTP errors).
Structure of the response:
- Introduction: Explain the libraries used (
newspaper3k for scraping, transformers for AI summarization).
- Prerequisites:
pip install commands.
- The Script: Complete code with comments.
- How it works: Brief explanation.
- Notes: Mentioning paywalls and ethical scraping.
Let's write the code mentally to check for bugs.
article.text might be very long. Transformer models usually have a token limit (e.g., 512 or 1024 tokens). If the article is long, the summarizer might crash.
I should truncate the text or use a model that handles long sequences (like LED) or simply warn the user. For a generic script, standard sshleifer/distilbart-cnn-12-6 (the default) is fine, but I'll add a chunk to truncate text to the first 1024 characters to prevent errors during the demo.
Actually, newspaper3k's text extraction is usually clean enough.
Let's go with the transformers approach as the primary one because "summarize" usually implies "abstractive" capabilities nowadays.
Wait, newspaper3k might be tricky to install on some Windows machines due to lxml dependencies. I should add a note about that.
But for a Python script request, assuming a standard environment is fine.
Let's prepare the final output.
Title: News Summarizer
Method: newspaper3k (scraping) + transformers (summarization).
Dependencies:
pip install newspaper3k transformers torch lxml
Script features:
- Input: List of URLs.
- Output: Title, Author, Summary.
Let's stick to one URL to keep the code simple to read, but mention how to loop.
Refined code logic:
import newspaper
from transformers import pipeline
def get_summary(url):
# 1. Scrape
article = newspaper.Article(url)
try:
article.download()
article.parse()
except Exception as e:
return f"Error downloading: {e}"
# 2. Prepare text (handle length limits)
text = article.text
if len(text) > 3000: # simple truncation for demo
text = text[:3000]
# 3. Summarize
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
return summary[0]['summary_text']
This looks solid. I will present this clearly.
One constraint: facebook/bart-large-cnn is heavy (1.6GB).
Maybe I should use sshleifer/distilbart-cnn-12-6 or google/pegasus-xsum. DistilBART is a good balance. Or just let pipeline default. The default is usually fine for a generic request.
Let's provide the Best Practice approach which involves using newspaper3k for the heavy lifting of scraping.
I will also add a warning about User-Agent headers. newspaper3k handles headers, but sometimes custom headers are needed. I'll keep it simple and rely on the library default first.
Final check of the request: "scrape news articles and summarize them".
The solution must do both.
One valid simplification: Use newspaper3k's internal nlp() function.
article.nlp() -> article.summary.
This is purely extractive (it picks sentences).
Is this what the user wants? "Summarize" often implies rewriting.
I will provide the AI-based (Transformers) version as the main answer because it is more impressive and useful, but I will mention the extractive method as a lightweight alternative.
Actually, for a "build a script" request, providing a modular script is best.
I'll structure the script to allow the user to switch between a simple summary and an AI summary.
Okay, plan set.
- Libraries:
newspaper3k, transformers, torch.
- Script: Scrape -> Check Length -> Summarize.
- Explanation.
Wait, newspaper3k hasn't been updated in a while and sometimes has issues with Python 3.10+. I should probably stick to the most robust path.
Actually, requests + BeautifulSoup is more reliable for scraping generally, but newspaper3k is magic for News specifically (it finds the author, publish date, and main body text automatically without writing CSS selectors).
I will stick with newspaper3k because scraping news manually requires writing specific parsers for every single news site (CNN looks different than NYT). newspaper3k solves this generic problem.
Let's write the response.
To build a robust news scraper and summarizer, the best approach involves two steps:
- Scraping: Use the
newspaper3k library. Unlike generic web scrapers, this library is specifically designed for news. It automatically detects the title, main text, author, and publication date, ignoring ads and navigation menus.
- Summarization: Use the
transformers library (by Hugging Face). This uses Deep Learning to generate an abstractive summary (writing new sentences that capture the meaning) rather than just extracting the first few sentences.
Prerequisites
You will need to install the following libraries via your terminal/command prompt:
pip install newspaper3k transformers torch sentencepiece
(Note: If you are on Linux, you might also need to run sudo apt-get install libxml2-dev libxslt-dev for parsing capabilities).
The Python Script
Save this code as news_summarizer.py.
import newspaper
from transformers import pipeline
def summarize_news_article(url):
"""
Scrapes a news article from a URL and generates an AI summary.
"""
print(f"--> Processing: {url}")
# 1. Scrape the Article
# 'language' can be set to other ISO 639-1 codes (e.g., 'fr', 'es')
try:
article = newspaper.Article(url, language='en')
article.download()
article.parse()
except Exception as e:
print(f"Error downloading article: {e}")
return
# Check if text was actually extracted
if not article.text:
print("Error: Could not extract text from the URL. It might be a video page or behind a paywall.")
return
print(f" Title: {article.title}")
print(f" Authors: {article.authors}")
# 2. Summarize the Text
# We use a pre-trained model from Hugging Face.
# 'facebook/bart-large-cnn' is excellent for news summarization.
# This might download the model weights on the first run (~1.6GB).
try:
print(" Generating summary (this may take a moment)...")
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
# Transformers have a token limit (usually 1024 tokens).
# We truncate the text to avoid errors on very long articles.
# Ideally, you would split text into chunks, but truncating is easier for a simple script.
max_input_length = 1024
summary_result = summarizer(
article.text,
max_length=150,
min_length=30,
do_sample=False,
truncation=True
)
summary_text = summary_result[0]['summary_text']
# 3. Output Results
print("\n" + "="*50)
print(f"SUMMARY: {summary_text}")
print("="*50 + "\n")
except Exception as e:
print(f"Error during summarization: {e}")
if __name__ == "__main__":
# Example URLs (Try different news sites to test)
urls_to_process = [
"https://www.cnn.com/2023/09/20/world/venezuela-lost-glacier/index.html",
"https://www.bbc.com/news/science-environment-64672861"
]
for url in urls_to_process:
summarize_news_article(url)
How it works
newspaper.Article(url): This object goes to the URL, downloads the HTML, and cleans it up. It performs "Article Extraction," separating the actual news story from the sidebar, footer, and ads.
pipeline("summarization"): This loads a pre-trained Deep Learning model (specifically BART, trained on CNN/Daily Mail news data).
summarizer(...): It takes the raw text from the scraper, encodes it, runs it through the neural network, and decodes the result into a coherent English summary.
Important Limitations
- Paywalls: This script cannot bypass paywalls (e.g., Wall Street Journal, Washington Post).
- JavaScript:
newspaper3k downloads the raw HTML. If a site renders its text purely via JavaScript (like a React app with no server-side rendering), the text might come back empty.
- Token Limits: The AI model has a limit on how much text it can read at once (approx. 1000 words). In this script, we set
truncation=True to cut off excess text. If you need to summarize entire books, you would need to implement a "chunking" logic to summarize parts individually.
- First Run: When you run this for the first time, it will download the AI model (approx. 1.6GB), so the first execution will be slow. Subsequent runs will be fast.