News API cho phép tìm kiếm và lấy bài báo từ nhiều nguồn. Cần API key (miễn phí tại newsapi.org).
Ví dụ cơ bản: Lấy top 10 tin BBC
import requests
def Topnews():
my_api_key = "YOUR_API_KEY" # Thay bằng key của bạn
my_url = f"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey={my_api_key}"
response = requests.get(my_url).json()
articles = response["articles"]
for i, article in enumerate(articles[:10], 1):
print(f"{i}. {article['title']}")
if __name__ == '__main__':
Topnews()
Lưu ý: API v1 trong bài gốc đã cũ, ví dụ trên dùng v2 (hiện tại).
Sử dụng Pandas DataFrame
Chuyển JSON sang DataFrame để dễ phân tích, lọc, xuất CSV/Excel.
import pandas as pd
import requests
response = requests.get(my_url).json()
df = pd.DataFrame(response['articles'])
print(df[['title', 'author', 'publishedAt', 'url']].head(10))
# df.to_csv('bbc_news.csv', index=False)