
構建基于Claude MCP的天氣查詢智能體 | 實戰落地示例
目前 Google 官方已不再開放傳統意義上的 Google News API,但我們可以通過以下方式實現相同目的:
方案類型 | 實現工具或平臺 | 特點說明 |
---|---|---|
非官方 API | SerpAPI(推薦) | 封裝 Google 新聞搜索結果,提供 JSON 格式 |
自行爬蟲 | BeautifulSoup + requests | 靈活但易被反爬,穩定性差 |
RSS 聚合 | Google News RSS Feed | 簡單易用,支持基礎訂閱 |
本文聚焦于使用 SerpAPI 這一最穩定、開發者友好的方式。
pip install google-search-results
或使用:
pip install serpapi
from serpapi import GoogleSearch
params = {
"engine": "google_news",
"q": "人工智能",
"api_key": "YOUR_API_KEY",
"hl": "zh-cn",
"gl": "cn",
"num": 10
}
search = GoogleSearch(params)
results = search.get_dict()
news = results.get("news_results", [])
for item in news:
print(f"標題:{item['title']}")
print(f"鏈接:{item['link']}")
print(f"摘要:{item['snippet']}")
print(f"來源:{item.get('source', {}).get('name')}")
print("-" * 30)
每條 news_results
包含字段:
title
: 新聞標題link
: 原始鏈接snippet
: 摘要source.name
: 新聞來源date
: 發布時間thumbnail
: 圖片(部分結果)import csv
with open("news.csv", "w", encoding="utf-8-sig", newline="") as f:
writer = csv.writer(f)
writer.writerow(["標題", "鏈接", "摘要", "來源", "時間"])
for item in news:
writer.writerow([
item["title"],
item["link"],
item["snippet"],
item.get("source", {}).get("name", ""),
item.get("date", "")
])
cron
每小時或每日調度;你可以基于 Google News API 獲取的數據,進一步構建智能功能:
使用 NLP 工具如 TextBlob、SnowNLP 或 OpenAI API,對每條新聞情緒進行打分:
from textblob import TextBlob
polarity = TextBlob(item["snippet"]).sentiment.polarity
結合關鍵字或機器學習算法對新聞進行分類,如財經、科技、娛樂、健康等。
將新聞摘要或原文輸入 GPT 模型,生成 60 字中文總結:
prompt = f"請用中文簡要總結以下新聞內容:{item['snippet']}"
問題類型 | 解決方案 |
---|---|
API 返回為空 | 檢查關鍵詞拼寫,或更換語言、地區參數 |
請求失敗 | 添加異常捕獲,設置重試機制 |
報錯 429 Too Many Requests |
設置 sleep,或升級到更高計劃 |
示例:
import time
from requests.exceptions import RequestException
try:
search = GoogleSearch(params)
results = search.get_dict()
except RequestException:
print("請求過多,等待 10 秒后重試")
time.sleep(10)
應用場景 | 實施方式 |
---|---|
輿情監控系統 | 自動抓取特定關鍵詞新聞,并結合情緒分析與關鍵詞抽取 |
內容采集平臺 | 按地域和主題分類匯總新聞,用于門戶、微信公眾號內容分發 |
金融情報抓取 | 關注股市變動、公司名稱新聞事件,結合行情預測模型 |
文章素材收集 | 抓取某個領域的最新新聞并自動整理摘要寫入 Notion |
平臺 | 免費額度 | 數據實時性 | 多語言支持 | 結構化數據 | 使用復雜度 |
---|---|---|---|---|---|
SerpAPI | ? 每月 100 條 | ? 優秀 | ? 多語種 | ? JSON | ??(易用) |
NewsAPI.org | ? 已不支持 Google News | ? 好 | ? 多語種 | ? JSON | ??? |
GNews.io | ? 限制較多 | ? 5\~15 分鐘延遲 | ? | ? | ?? |
RSS Feed 抓取 | ? | ? 緩慢 | ? | ? HTML | ???? |
結論:在抓取 Google 新聞這一垂直領域,SerpAPI 是目前最穩定、最易用的開發者解決方案。
通過本文你已掌握: