Creating a newspaper reader in Python can involve fetching articles from a news API, parsing the data, and presenting it in a readable format. Below is an example of how you can create a simple newspaper reader using the requests
library to fetch data from the NewsAPI and the json
library to handle the data.
First, you’ll need to sign up for an API key at NewsAPI.
Table of Contents
Here is a basic implementation:
Install the required library for Newspaper Reader:
pip install requests
Python Script:
import requests
import json
def fetch_news(api_key, category='general', country='us'):
url = f"https://newsapi.org/v2/top-headlines?category={category}&country={country}&apiKey={api_key}"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch news: {response.status_code}")
return None
def display_news(news_data):
if news_data and 'articles' in news_data:
articles = news_data['articles']
for index, article in enumerate(articles):
print(f"{index + 1}. {article['title']}")
print(f" Source: {article['source']['name']}")
print(f" Author: {article.get('author', 'Unknown')}")
print(f" Description: {article['description']}")
print(f" URL: {article['url']}")
print("\n")
else:
print("No news available")
def main():
api_key = 'YOUR_API_KEY' # Replace with your NewsAPI key
category = 'technology' # Change category as needed
country = 'us' # Change country as needed
news_data = fetch_news(api_key, category, country)
display_news(news_data)
if __name__ == "__main__":
main()
Explanation:
- fetch_news: This function fetches news data from NewsAPI. You can specify the category (like ‘technology’, ‘sports’, etc.) and country code (like ‘us’ for the United States) to tailor the news to your preference.
- display_news: This function formats and displays the fetched news articles.
- main: This function sets up the parameters and calls the other functions to fetch and display the news.
Running the script:
- Replace
'YOUR_API_KEY'
with your actual NewsAPI key. - Customize the
category
andcountry
parameters if needed. - Run the script.
This script fetches the top headlines in the specified category and country, then prints out the title, source, author, description, and URL for each article.
If you need further customization or advanced features like saving articles or filtering by keywords, you can expand on this basic structure.
pyscreenshot Taking Screenshots with Python and Easy and fast