News Aggregator
Abstract
News Aggregator is a Python application that fetches and displays the latest news headlines from multiple sources using public APIs. It demonstrates API integration, data parsing, and GUI development with Tkinter. This project is ideal for learning about REST APIs, JSON handling, and building interactive desktop apps.
Prerequisites
- Python 3.6 or above
- requests module (
pip install requests
pip install requests
) - tkinter (usually pre-installed)
- Internet connection
Before you Start
Before starting, ensure you have Python and a code editor installed. Install the requests
requests
library using pip install requests
pip install requests
. Obtain a free API key from NewsAPI.
Getting Started
- Create a folder named
news-aggregator
news-aggregator
. - Create a file named
news_aggregator.py
news_aggregator.py
. - Copy the code below into your file.
⚙️ News Aggregator
News Aggregator
"""
News Aggregator
A news aggregator application with the following features:
- Fetch news articles from multiple sources using RSS feeds or APIs
- Categorize news articles by topic (e.g., technology, sports, etc.)
- Search functionality to find specific articles
- Save favorite articles for later reading
"""
import feedparser
from tkinter import Tk, Label, Entry, Button, Listbox, Scrollbar, StringVar, messagebox
class NewsAggregator:
def __init__(self, root):
self.root = root
self.root.title("News Aggregator")
self.feeds = {
"Technology": "https://rss.nytimes.com/services/xml/rss/nyt/Technology.xml",
"Sports": "https://rss.nytimes.com/services/xml/rss/nyt/Sports.xml",
"World": "https://rss.nytimes.com/services/xml/rss/nyt/World.xml",
}
self.articles = []
self.selected_feed = StringVar(value="Technology")
self.setup_ui()
def setup_ui(self):
"""Set up the user interface."""
Label(self.root, text="Select Category:").pack(pady=5)
for category in self.feeds.keys():
Button(self.root, text=category, command=lambda c=category: self.fetch_articles(c)).pack(pady=2)
Label(self.root, text="Articles:").pack(pady=5)
self.article_list = Listbox(self.root, width=80, height=20)
self.article_list.pack(pady=5)
scrollbar = Scrollbar(self.article_list)
scrollbar.pack(side="right", fill="y")
Button(self.root, text="View Article", command=self.view_article).pack(pady=5)
Button(self.root, text="Save to Favorites", command=self.save_to_favorites).pack(pady=5)
def fetch_articles(self, category):
"""Fetch articles from the selected category."""
feed_url = self.feeds.get(category)
if not feed_url:
messagebox.showerror("Error", "Invalid category selected.")
return
try:
feed = feedparser.parse(feed_url)
self.articles = feed.entries
self.article_list.delete(0, "end")
for article in self.articles:
self.article_list.insert("end", article.title)
messagebox.showinfo("Success", f"Fetched {len(self.articles)} articles from {category}.")
except Exception as e:
messagebox.showerror("Error", f"Failed to fetch articles: {e}")
def view_article(self):
"""View the selected article."""
selected_index = self.article_list.curselection()
if not selected_index:
messagebox.showerror("Error", "No article selected.")
return
article = self.articles[selected_index[0]]
messagebox.showinfo("Article", f"Title: {article.title}\n\n{article.summary}")
def save_to_favorites(self):
"""Save the selected article to favorites."""
selected_index = self.article_list.curselection()
if not selected_index:
messagebox.showerror("Error", "No article selected.")
return
article = self.articles[selected_index[0]]
with open("favorites.txt", "a") as file:
file.write(f"{article.title}\n{article.link}\n\n")
messagebox.showinfo("Success", "Article saved to favorites.")
def main():
root = Tk()
app = NewsAggregator(root)
root.mainloop()
if __name__ == "__main__":
main()
News Aggregator
"""
News Aggregator
A news aggregator application with the following features:
- Fetch news articles from multiple sources using RSS feeds or APIs
- Categorize news articles by topic (e.g., technology, sports, etc.)
- Search functionality to find specific articles
- Save favorite articles for later reading
"""
import feedparser
from tkinter import Tk, Label, Entry, Button, Listbox, Scrollbar, StringVar, messagebox
class NewsAggregator:
def __init__(self, root):
self.root = root
self.root.title("News Aggregator")
self.feeds = {
"Technology": "https://rss.nytimes.com/services/xml/rss/nyt/Technology.xml",
"Sports": "https://rss.nytimes.com/services/xml/rss/nyt/Sports.xml",
"World": "https://rss.nytimes.com/services/xml/rss/nyt/World.xml",
}
self.articles = []
self.selected_feed = StringVar(value="Technology")
self.setup_ui()
def setup_ui(self):
"""Set up the user interface."""
Label(self.root, text="Select Category:").pack(pady=5)
for category in self.feeds.keys():
Button(self.root, text=category, command=lambda c=category: self.fetch_articles(c)).pack(pady=2)
Label(self.root, text="Articles:").pack(pady=5)
self.article_list = Listbox(self.root, width=80, height=20)
self.article_list.pack(pady=5)
scrollbar = Scrollbar(self.article_list)
scrollbar.pack(side="right", fill="y")
Button(self.root, text="View Article", command=self.view_article).pack(pady=5)
Button(self.root, text="Save to Favorites", command=self.save_to_favorites).pack(pady=5)
def fetch_articles(self, category):
"""Fetch articles from the selected category."""
feed_url = self.feeds.get(category)
if not feed_url:
messagebox.showerror("Error", "Invalid category selected.")
return
try:
feed = feedparser.parse(feed_url)
self.articles = feed.entries
self.article_list.delete(0, "end")
for article in self.articles:
self.article_list.insert("end", article.title)
messagebox.showinfo("Success", f"Fetched {len(self.articles)} articles from {category}.")
except Exception as e:
messagebox.showerror("Error", f"Failed to fetch articles: {e}")
def view_article(self):
"""View the selected article."""
selected_index = self.article_list.curselection()
if not selected_index:
messagebox.showerror("Error", "No article selected.")
return
article = self.articles[selected_index[0]]
messagebox.showinfo("Article", f"Title: {article.title}\n\n{article.summary}")
def save_to_favorites(self):
"""Save the selected article to favorites."""
selected_index = self.article_list.curselection()
if not selected_index:
messagebox.showerror("Error", "No article selected.")
return
article = self.articles[selected_index[0]]
with open("favorites.txt", "a") as file:
file.write(f"{article.title}\n{article.link}\n\n")
messagebox.showinfo("Success", "Article saved to favorites.")
def main():
root = Tk()
app = NewsAggregator(root)
root.mainloop()
if __name__ == "__main__":
main()
- Run the script:
python news_aggregator.py
python news_aggregator.py
Explanation
Code Breakdown
- Import modules
import requests
import tkinter as tk
import requests
import tkinter as tk
- Fetch news from API
def fetch_news():
url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY'
response = requests.get(url)
data = response.json()
return [article['title'] for article in data['articles']]
def fetch_news():
url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY'
response = requests.get(url)
data = response.json()
return [article['title'] for article in data['articles']]
- Display headlines in GUI
root = tk.Tk()
root.title('News Aggregator')
listbox = tk.Listbox(root, width=80)
listbox.pack(pady=20)
for headline in fetch_news():
listbox.insert(tk.END, headline)
root.mainloop()
root = tk.Tk()
root.title('News Aggregator')
listbox = tk.Listbox(root, width=80)
listbox.pack(pady=20)
for headline in fetch_news():
listbox.insert(tk.END, headline)
root.mainloop()
Features
- Fetches latest headlines from multiple sources
- Simple Tkinter GUI for display
- Easy to extend for more sources
- Demonstrates API and JSON usage
How It Works
- Uses requests to call news API
- Parses JSON response
- Displays headlines in a listbox
GUI Components
- Listbox: Shows headlines
- Window Title: News Aggregator
- Padding: For readability
Use Cases
- Stay updated with news
- Learn API integration
- Build custom news dashboards
Next Steps
You can enhance this project by:
- Adding more news sources
- Displaying summaries and images
- Implementing search/filter
- Saving favorite articles
- Adding refresh button
- Supporting multiple countries/languages
Enhanced Version Ideas
def fetch_news_with_images():
# Fetch headlines and images
pass
def search_news(query):
# Search for news by keyword
pass
def fetch_news_with_images():
# Fetch headlines and images
pass
def search_news(query):
# Search for news by keyword
pass
Troubleshooting Tips
- API key errors: Check your key
- No headlines: Check internet connection
- GUI not showing: Ensure Tkinter is installed
Conclusion
This project teaches API usage, JSON parsing, and GUI basics. Extend it for more features and sources. Great for learning real-world Python and desktop app development.
Was this page helpful?
Let us know how we did