News Aggregator


  • Visit NewsAPI and sign up for a free API key.
  • Replace your_newsapi_key in the code with your actual API key.

  •  import requests

    API_KEY = "your_newsapi_key"  # Replace with your NewsAPI key

    BASE_URL = "https://newsapi.org/v2/"


    def fetch_top_headlines(country="us", category="general", page_size=5):

        """

        Fetch top news headlines from NewsAPI.

        Args:

            country (str): Country code for news (default is 'us').

            category (str): Category of news (default is 'general').

            page_size (int): Number of headlines to fetch (default is 5).

        Returns:

            list: A list of dictionaries containing news headlines and details.

        """

        url = f"{BASE_URL}top-headlines"

        params = {

            "apiKey": API_KEY,

            "country": country,

            "category": category,

            "pageSize": page_size,

        }

        try:

            response = requests.get(url, params=params)

            response.raise_for_status()

            data = response.json()

            return data.get("articles", [])

        except requests.exceptions.RequestException as e:

            print(f"Error fetching news: {e}")

            return []


    def display_headlines(articles):

        """

        Display news headlines in a user-friendly format.


        Args:

            articles (list): List of news articles.

        """

        if not articles:

            print("No news articles found.")

            return

        print("\n--- Latest News Headlines ---")

        for idx, article in enumerate(articles, 1):

            print(f"\n{idx}. {article['title']}")

            print(f"   Source: {article['source']['name']}")

            print(f"   URL: {article['url']}")


    def main():

        print("Welcome to the News Aggregator!")

        country = input("Enter the country code for news (e.g., 'us' for USA, 'in' for India): ").strip()

        category = input("Enter the category of news (e.g., 'business', 'entertainment', 'sports'): ").strip()

        num_articles = input("How many articles would you like to fetch? (default is 5): ").strip()


        # Default values if input is empty

        country = country if country else "us"

        category = category if category else "general"

        num_articles = int(num_articles) if num_articles.isdigit() else 5


        print("\nFetching top headlines...")

        articles = fetch_top_headlines(country=country, category=category, page_size=num_articles)


        display_headlines(articles)


    if __name__ == "__main__":

        main()


    No comments: