Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ดึงข่าว hàngวันด้วย News API ใน Python

News API เป็น API ยอดนิยมสำหรับค้นหาและดึงบทความข่าวจากเว็บไซต์ต่างๆ โดยใช้ API นี้สามารถดึงหัวข้อข่าว hàngวันได้ 10 หัวข้อจากแหล่งข่าวใดก็ได้

แต่การใช้ API นี้ต้องมี API Key ซึ่งต้องสมัครสมาชิกที่ newsapi.org ก่อน

โค้ดตัวอย่าง: ดึงข่าวจาก BBC

import requests

def Topnews():
    # BBC news api - ต้องใส่ API Key จริงของคุณ
    my_api_key = "YOUR_API_KEY_HERE"
    my_url = f"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey={my_api_key}"
    
    my_open_bbc_page = requests.get(my_url).json()
    my_article = my_open_bbc_page["articles"]
    my_results = []
    
    for ar in my_article:
        my_results.append(ar["title"])
    
    for i in range(len(my_results)):
        print(i + 1, my_results[i])

if __name__ == '__main__':
    Topnews()

หมายเหตุ: URL ในตัวอย่างเดิมใช้ API v1 ซึ่งล้าสมัยแล้ว ตัวอย่างด้านบนอัปเดตเป็น v2 แล้ว

การใช้งานกับ Pandas DataFrame

การใช้ pandas DataFrame ทำให้การจัดการข้อมูลง่ายขึ้น สามารถแปลงจาก JSON เป็น DataFrame ได้ด้วย pd.DataFrame.from_dict และ .apply(pd.Series)

import requests
import pandas as pd

def get_news_dataframe():
    api_key = "YOUR_API_KEY_HERE"
    url = f"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey={api_key}"
    
    response = requests.get(url).json()
    articles = response["articles"]
    
    # แปลงเป็น DataFrame
    df = pd.DataFrame(articles)
    return df[['title', 'description', 'url', 'publishedAt']]

# ใช้งาน
df = get_news_dataframe()
print(df.head())

ดึงข่าว hàngวันด้วย News API ใน Python
ดึงข่าว hàngวันด้วย News API ใน Python

ข้อแนะนำ: ควรเก็บ API Key ในตัวแปรสภาพแวดล้อม (environment variable) แทนการเขียนฮาร์ดโค้ดในโค้ด