15 – Real-World Python Projects – News Aggregator

🎯 Project Objective

To build a News Aggregator Application that automatically fetches and displays the latest news headlines from multiple online sources using APIs or web scraping.

Skills Demonstrated:

  • Working with APIs (requests, json)
  • Parsing and structuring data
  • GUI creation using Tkinter
  • File handling and optional CSV export
  • Error handling and API rate-limit management

🧠 Project Overview

The News Aggregator App allows users to:

  • Fetch top news headlines from multiple sources (e.g., BBC, CNN, TechCrunch, etc.)
  • Filter news by category (Technology, Business, Sports, Entertainment)
  • Display results in a clean, scrollable GUI
  • Optionally save news summaries to a file for later reading

Real-Life Applications:

  • Personalized news dashboard
  • Daily summary emailer
  • Stock/crypto news monitor
  • AI summarizer or alert system backend

βš™οΈ Technology Stack

LibraryPurpose
requestsTo call news APIs
jsonParse API responses
tkinterGUI development
pandas (optional)Export news data
datetimeTimestamp logs

🧩 Example Code – News Aggregator (Tkinter + NewsAPI)

Note: This script auto-installs missing modules.

import os
import sys
import subprocess

# βœ… Auto-install missing packages
def install(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])

install("requests")
install("tkinter")

import requests
import tkinter as tk
from tkinter import messagebox, scrolledtext
from datetime import datetime

# Replace with your free API key from https://newsapi.org/
API_KEY = "your_api_key_here"

def fetch_news(category="general"):
    url = f"https://newsapi.org/v2/top-headlines?country=us&category={category}&apiKey={API_KEY}"
    try:
        response = requests.get(url)
        data = response.json()

        if data["status"] != "ok":
            messagebox.showerror("Error", "Failed to fetch news.")
            return

        news_box.delete(1.0, tk.END)  # Clear previous text
        for article in data["articles"][:10]:  # Show top 10
            title = article["title"]
            source = article["source"]["name"]
            url = article["url"]
            description = article["description"]
            news_box.insert(tk.END, f"πŸ—žοΈ {title}\nπŸ“ Source: {source}\nπŸ”— {url}\nπŸ“ {description}\n\n")
        news_box.insert(tk.END, f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

    except Exception as e:
        messagebox.showerror("Error", f"Could not retrieve news: {e}")

# GUI setup
root = tk.Tk()
root.title("πŸ“° News Aggregator App")
root.geometry("600x500")
root.config(bg="#f0f0f0")

tk.Label(root, text="Select News Category:", font=("Arial", 12, "bold"), bg="#f0f0f0").pack(pady=10)

categories = ["general", "business", "technology", "sports", "entertainment", "science", "health"]
category_var = tk.StringVar(value="general")
category_menu = tk.OptionMenu(root, category_var, *categories)
category_menu.pack()

tk.Button(root, text="Fetch News", command=lambda: fetch_news(category_var.get()),
          font=("Arial", 12), bg="#2196F3", fg="white").pack(pady=10)

news_box = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=70, height=20, font=("Arial", 10))
news_box.pack(padx=10, pady=10)

root.mainloop()

🧾 Sample Output

Category: Technology

πŸ—žοΈ Google Launches New AI Model for Developers
πŸ“ Source: TechCrunch
πŸ”— https://techcrunch.com/ai-launch
πŸ“ The new model enhances productivity and AI-based automation.

πŸ—žοΈ Apple Reveals New MacBook Lineup
πŸ“ Source: BBC News
πŸ”— https://bbc.co.uk/macbook
πŸ“ Apple introduces faster M3 chips for creative professionals.

πŸ”§ How It Works

  1. User selects a category (e.g., β€œtechnology”).
  2. App calls NewsAPI with the selected parameter.
  3. JSON response contains headline data.
  4. GUI displays the top stories with titles, sources, and URLs.

🌍 API Setup

  1. Visit https://newsapi.org/
  2. Sign up and generate a free API key
  3. Replace: API_KEY = "your_api_key_here"
  4. Run the script β€” your news app goes live! πŸš€

πŸ’Ύ Optional – Export Headlines

Add this snippet after fetch_news() to save results to a file:

with open("latest_news.txt", "w", encoding="utf-8") as file:
    for article in data["articles"]:
        file.write(f"{article['title']} - {article['source']['name']}\n")

βœ… You can later upgrade it to export CSV or Excel using pandas.


🧩 Advanced Features to Try

  • 🌍 Add language or country filter
  • πŸ” Add keyword search bar
  • πŸ•’ Auto-refresh every 15 minutes
  • πŸ’Ύ Save favorite articles locally
  • πŸ“± Build a mobile/web version using Flask or Kivy

βœ… Key Takeaways

  • Integrating and using third-party APIs
  • Parsing structured JSON data
  • Building GUI interfaces for real-time content
  • Managing user input and errors gracefully
  • Creating professional-grade data tools

🧠 Learning Outcomes

After completing this project, you’ll be able to:

  • Connect Python applications with live API data
  • Build interactive interfaces for real-world use
  • Extend your app into dashboards or personal productivity tools

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *