Generating Python script for news scraping
The user wants a Python script to scrape and summarize news articles, and I need to design it generically. I could consider using libraries like newspaper3k or BeautifulSoup for scraping, and gensim or sumy for summarization. I must keep ethics in mind, mentioning the importance of respecting robots.txt and site terms. I should also provide an end-to-end example showing how to define RSS feeds, fetch articles, and summarize them, possibly integrating optional LLM summarization.Designing news scraping instructions
I need to instruct the user to install key dependencies like requests, BeautifulSoup4, newspaper3k, and possibly NLTK. I might suggest using feedparser to get the latest article URLs from RSS feeds, which is more reliable than scraping arbitrary HTML structures. For a generic Python script, I’ll outline steps: first, install dependencies, then create a script that includes a list of news site URLs. I’ll show how to parse those URLs and download article text using newspaper3k, followed by a summarization method with NLTK.Designing a simple summarization script
The user wants a straightforward script without a GUI, so I need to respect that. I’ll add comments and a docstring to ensure clarity and adherence to terms of service. For the summarization method, I’ll implement a basic extractive approach. I plan to tokenize the input text, remove stopwords and punctuation, and create a frequency distribution. Then, I’ll score and sort sentences to select the top five for the summary. Also, I should include checks for any necessary NLTK data downloads while keeping the complexity minimal.Building a simple news scraper
I could keep this simple by having the script contain a list of RSS feeds for easy access. While I could demonstrate how to run it from the command line with a URL, it might be more educational to allow input for search queries or specific sites. However, since the user wants to generically scrape news articles, using RSS feeds seems the best route. So, I’ll propose Option 1 with a list of RSS feeds and a function to get article links, ensuring we include necessary dependencies like newspaper3k and feedparser.Crafting the news scraper disclaimer and structure
I need to include disclaimers about my knowledge being up to date as of 2024 and mention that some feed names may change, like Reuters. While feedparser must be installed with pip install feedparser newspaper3k, I’ll clarify that newspaper3k has its dependencies. To keep it straightforward, I’ll suggest those commands and highlight summarization handled internally. Also, I should make sure the code is compatible with older versions like 3.8, avoiding complex typing. Finally, my structure will include steps and clear instructions in plain English, with code blocks included. Here’s a complete example of a Python script that:
- Pulls articles from a few example news RSS feeds
- Extracts the full article text
- Creates a simple extractive summary (no external ML models)
- Prints title, URL, and summary
You can easily adapt the list of feeds to whatever sites you care about.
1. Install requirements
pip install feedparser newspaper3k
Note: Always review and follow each site’s Terms of Service and robots.txt before scraping, and keep request volumes low.
2. news_scraper.py
#!/usr/bin/env python3
"""
Simple news scraper and summarizer.
- Fetches recent articles from RSS feeds
- Downloads and parses article content
- Produces a short extractive summary
Dependencies:
pip install feedparser newspaper3k
"""
import time
import re
from collections import Counter
from urllib.parse import urlparse
import feedparser
from newspaper import Article
# ---------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------
# Example RSS feeds — replace or add your own
NEWS_FEEDS = [
"https://feeds.bbci.co.uk/news/rss.xml",
"https://rss.cnn.com/rss/edition.rss",
"https://feeds.reuters.com/reuters/topNews",
]
ARTICLES_PER_FEED = 3 # how many articles to pull from each feed
SUMMARY_SENTENCES = 4 # how many sentences per summary
REQUEST_DELAY_SEC = 1.0 # delay between article downloads (be polite)
# Simple English stopword list for summarization
STOPWORDS = {
"the", "a", "an", "and", "or", "but", "if", "while", "with", "to", "of",
"in", "on", "for", "at", "by", "from", "up", "down", "out", "over", "under",
"again", "further", "then", "once", "here", "there", "all", "any", "both",
"each", "few", "more", "most", "other", "some", "such", "no", "nor", "not",
"only", "own", "same", "so", "than", "too", "very", "can", "will", "just",
"don", "should", "now", "is", "are", "was", "were", "be", "been", "being",
"have", "has", "had", "do", "does", "did", "this", "that", "these", "those",
"it", "its", "i", "you", "he", "she", "they", "them", "we", "us", "my",
"your", "their", "our", "as", "about", "into", "through", "during", "before",
"after", "above", "below", "between", "because", "what", "which", "who",
"whom", "where", "when", "why", "how"
}
# ---------------------------------------------------------------------
# Article fetching
# ---------------------------------------------------------------------
def get_articles_from_feed(feed_url, limit=5):
"""
Fetch article metadata from an RSS feed and download each article.
Returns a list of dicts:
{
"title": str,
"url": str,
"text": str,
"published": str or None,
"source": str
}
"""
print(f"\n[+] Fetching feed: {feed_url}")
feed = feedparser.parse(feed_url)
articles = []
for entry in feed.entries[:limit]:
url = entry.get("link")
if not url:
continue
print(f" - Downloading article: {url}")
article_data = download_article(url)
if not article_data:
continue
article_data["published"] = entry.get("published")
article_data["source"] = urlparse(feed_url).netloc
articles.append(article_data)
time.sleep(REQUEST_DELAY_SEC) # politeness delay
return articles
def download_article(url):
"""
Download and parse a single article using newspaper3k.
Returns dict with "title", "url", "text", or None on failure.
"""
try:
article = Article(url)
article.download()
article.parse()
except Exception as e:
print(f" ! Failed to download/parse: {e}")
return None
text = (article.text or "").strip()
if not text:
print(" ! No text extracted; skipping.")
return None
return {
"title": article.title or "(no title)",
"url": url,
"text": text,
}
# ---------------------------------------------------------------------
# Simple extractive summarizer
# ---------------------------------------------------------------------
def summarize_text(text, max_sentences=4):
"""
Very simple frequency-based extractive summarizer.
- Splits text into sentences
- Scores sentences by the frequency of informative words
- Returns the top `max_sentences` sentences in original order
"""
# Basic sentence splitting
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
sentences = [s.strip() for s in sentences if s.strip()]
if len(sentences) <= max_sentences:
return " ".join(sentences)
# Word frequency analysis
words = re.findall(r'\w+', text.lower())
freqs = Counter(
w for w in words
if w not in STOPWORDS and len(w) > 3 # filter stopwords and very short words
)
if not freqs:
return " ".join(sentences[:max_sentences])
max_freq = max(freqs.values())
weights = {w: f / max_freq for w, f in freqs.items()}
# Score sentences
scored_sentences = []
for idx, sent in enumerate(sentences):
sent_words = re.findall(r'\w+', sent.lower())
if not sent_words:
continue
score = sum(weights.get(w, 0.0) for w in sent_words) / len(sent_words)
scored_sentences.append((score, idx, sent))
# Select top N sentences, keeping original order
top = sorted(scored_sentences, key=lambda x: x[0], reverse=True)[:max_sentences]
top_sorted_by_position = [s for (_score, _idx, s) in sorted(top, key=lambda x: x[1])]
return " ".join(top_sorted_by_position)
# ---------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------
def main():
all_articles = []
for feed_url in NEWS_FEEDS:
articles = get_articles_from_feed(feed_url, limit=ARTICLES_PER_FEED)
all_articles.extend(articles)
print("\n" + "=" * 80)
print("Summaries")
print("=" * 80)
for art in all_articles:
summary = summarize_text(art["text"], max_sentences=SUMMARY_SENTENCES)
print("\n" + "-" * 80)
print(f"Title : {art['title']}")
print(f"Source : {art.get('source')}")
print(f"Published: {art.get('published')}")
print(f"URL : {art['url']}")
print("\nSummary:")
print(summary)
print("-" * 80)
if __name__ == "__main__":
main()
3. Run it
python news_scraper.py
You’ll see summaries printed to the console for a few recent articles from each feed.
If you tell me which specific news site(s) you want to target or how you’d like to store the results (JSON, CSV, database, etc.), I can tailor the script further.