Python에서 실시간 뉴스를 가져오는 방법 (실용적인 예제 3개)
Source: Dev.to
번역을 진행하려면 번역하고자 하는 전체 텍스트를 제공해 주세요. 코드 블록이나 URL은 그대로 유지하고, 본문 내용만 한국어로 번역해 드리겠습니다.
Prerequisites
-
Python 3.7+
-
requests라이브러리pip install requests -
무료 API 키는 NewsMesh (무료 티어 사용 가능)에서 얻을 수 있습니다.
예시 1: 트렌딩 뉴스 가져오기
import requests
API_KEY = "your_api_key_here"
BASE_URL = "https://api.newsmesh.co/v1"
def get_trending_news(limit: int = 10):
"""Fetch currently trending news articles."""
response = requests.get(
f"{BASE_URL}/trending",
params={"apiKey": API_KEY, "limit": limit}
)
response.raise_for_status()
return response.json()["data"]
# Usage
for article in get_trending_news():
print(f"📰 {article['title']}")
print(f" Source: {article['source']} | Category: {article['category']}")
print(f" Link: {article['link']}\n")
샘플 출력
📰 Fed Signals Rate Cut in Early 2025
Source: Reuters | Category: business
Link: https://reuters.com/...
📰 OpenAI Announces GPT‑5 Preview
Source: TechCrunch | Category: technology
Link: https://techcrunch.com/...
예시 2: 카테고리와 국가별 뉴스 필터링
def get_latest_news(category: str | None = None,
country: str | None = None,
limit: int = 10):
"""
Fetch latest news with optional filters.
Args:
category: politics, technology, business, health, entertainment,
sports, science, lifestyle, environment, world
country: ISO code like 'us', 'gb', 'de', 'fr', etc.
limit: max 25 articles per request
"""
params = {"apiKey": API_KEY, "limit": limit}
if category:
params["category"] = category
if country:
params["country"] = country
response = requests.get(f"{BASE_URL}/latest", params=params)
response.raise_for_status()
return response.json()["data"]
# Technology news from the US
tech_news = get_latest_news(category="technology", country="us")
# Sports news from the UK
uk_sports = get_latest_news(category="sports", country="gb")
# All business news (max 25)
business = get_latest_news(category="business", limit=25)
사용 가능한 카테고리
| 카테고리 | 설명 |
|---|---|
politics | 정치 뉴스 |
technology | 기술, 스타트업, 가젯 |
business | 시장, 금융, 경제 |
health | 의료, 웰빙 |
entertainment | 연예인, 영화, 음악 |
sports | 전체 스포츠 보도 |
science | 과학적 발견 |
lifestyle | 문화, 트렌드 |
environment | 기후, 지속 가능성 |
world | 국제 뉴스 |
지원되는 국가
35개 이상의 국가, 예: us, gb, ca, au, de, fr, jp, in, br 등.
예시 3: 키워드로 뉴스 검색
def search_news(query: str,
from_date: str | None = None,
to_date: str | None = None,
sort_by: str = "date_descending"):
"""
Search news articles by keyword.
Args:
query: Search term (e.g., "bitcoin", "climate change")
from_date: Start date as YYYY‑MM‑DD
to_date: End date as YYYY‑MM‑DD
sort_by: 'date_descending', 'date_ascending', or 'relevant'
"""
params = {
"apiKey": API_KEY,
"q": query,
"sortBy": sort_by,
"limit": 25
}
if from_date:
params["from"] = from_date
if to_date:
params["to"] = to_date
response = requests.get(f"{BASE_URL}/search", params=params)
response.raise_for_status()
return response.json()["data"]
# Search for Bitcoin news from the last week
bitcoin_news = search_news(
query="bitcoin",
from_date="2024-12-23",
sort_by="relevant"
)
for article in bitcoin_news[:5]:
print(f"• {article['title']}")
print(f" {article['published_date'][:10]} - {article['source']}\n")
보너스: 간단한 뉴스 모니터링 스크립트
특정 키워드를 모니터링하고 새로운 기사가 나타날 때마다 출력하는 실용적인 스크립트입니다.
import requests
import time
from datetime import datetime
API_KEY = "your_api_key_here"
KEYWORDS = ["AI", "OpenAI", "GPT"] # Topics to monitor
CHECK_INTERVAL = 300 # Check every 5 minutes
seen_articles = set()
def check_for_news():
"""Check for new articles matching our keywords."""
for keyword in KEYWORDS:
response = requests.get(
"https://api.newsmesh.co/v1/search",
params={"apiKey": API_KEY, "q": keyword, "limit": 5}
)
if response.status_code != 200:
continue
for article in response.json().get("data", []):
article_id = article["article_id"]
if article_id not in seen_articles:
seen_articles.add(article_id)
print(f"\n🔔 NEW: {article['title']}")
print(f" Keyword: {keyword} | Source: {article['source']}")
if __name__ == "__main__":
while True:
check_for_news()
time.sleep(CHECK_INTERVAL)
print(f" Link: {article['link']}")
if __name__ == "__main__":
print(f"Monitoring news for: {', '.join(KEYWORDS)}")
print("Press Ctrl+C to stop\n")
while True:
check_for_news()
time.sleep(CHECK_INTERVAL)
페이지네이션 처리
25개 이상의 기사을 가져오려면 응답에 포함된 next_cursor 를 사용하세요:
def get_all_articles(category, max_articles=100):
"""Fetch multiple pages of articles."""
all_articles = []
cursor = None
while len(all_articles) < max_articles:
params = {"apiKey": API_KEY, "category": category, "limit": 25}
if cursor:
params["cursor"] = cursor
response = requests.get(f"{BASE_URL}/latest", params=params)
data = response.json()
all_articles.extend(data["data"])
cursor = data.get("next_cursor")
if not cursor: # No more pages
break
return all_articles[:max_articles]
오류 처리 모범 사례
항상 API 오류를 우아하게 처리하세요:
def safe_api_call(endpoint, params):
"""Make API call with proper error handling."""
try:
response = requests.get(endpoint, params=params, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
print("Request timed out. Try again.")
return None
except requests.exceptions.HTTPError as e:
error_data = e.response.json()
print(f"API Error: {error_data.get('message', 'Unknown error')}")
return None
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
무엇을 만들 수 있나요?
다음은 몇 가지 아이디어입니다:
- News digest bot – 관심 있는 주제에 대한 일일 이메일/Slack 요약
- Trading signals – 실시간으로 금융 뉴스를 반응
- Content aggregator – 나만의 Google News 만들기
- Research tool – 특정 기업이나 주제에 대한 보도를 추적
- News widget – 웹사이트에 실시간 뉴스 피드 추가
마무리
Python에서 뉴스를 가져오는 것은 신뢰할 수 있는 API만 있으면 간단합니다. 위 예제들은 빠르게 시작하는 데 도움이 될 것입니다.
리소스
뉴스 데이터를 가지고 무엇을 만들고 있나요? 아래에 댓글을 남겨 주세요 – 여러분의 프로젝트를 듣고 싶어요!