
如何在Python中使用ChatGPT API?
由于 Google 官方 News API 已停用,目前主流選擇包括:
方案類型 | 工具推薦 | 特點說明 |
---|---|---|
第三方 API | SerpAPI、Zenserp | 提供結構化 JSON 數據,穩定可靠 |
RSS 抓取 | Google News RSS | 免費但信息粒度有限 |
自建爬蟲 | Python+BeautifulSoup | 靈活但存在反爬挑戰 |
在實際部署中,SerpAPI 是最推薦的解決方案,具備高效、結構清晰、支持語言和區域過濾等優勢。
from serpapi import GoogleSearch
params = {
"engine": "google_news",
"q": "人工智能",
"hl": "zh-cn",
"gl": "cn",
"num": 20,
"api_key": "YOUR_SERPAPI_KEY"
}
search = GoogleSearch(params)
results = search.get_dict()
news = results.get("news_results", [])
返回字段說明:
title
: 新聞標題link
: 原文鏈接snippet
: 簡要內容source.name
: 來源媒體date
: 發布時間使用 jieba
對標題與摘要進行分詞:
import jieba
from collections import Counter
text = " ".join(item["title"] for item in news)
words = [w for w in jieba.cut(text) if len(w) > 1]
top_words = Counter(words).most_common(20)
可視化詞頻:
使用 wordcloud
生成關鍵詞圖譜,快速洞察話題聚焦點。
將摘要轉向量化后聚類:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
texts = [item["snippet"] for item in news]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)
model = KMeans(n_clusters=5, random_state=42)
labels = model.fit_predict(X)
結果可將新聞自動分組,例如:
將新聞日期歸類后統計關鍵詞出現頻率,生成趨勢曲線圖:
import matplotlib.pyplot as plt
from collections import defaultdict
trend = defaultdict(int)
for item in news:
date = item.get("date", "未知")
if "小時" not in date:
trend[date] += 1
plt.plot(list(trend.keys()), list(trend.values()))
plt.xticks(rotation=45)
plt.title("新聞熱度趨勢")
plt.show()
使用 SnowNLP
或 TextBlob
分析摘要的情緒傾向:
from snownlp import SnowNLP
for item in news:
score = SnowNLP(item["snippet"]).sentiments
item["sentiment"] = "正面" if score > 0.6 else "負面" if score < 0.4 else "中性"
? 正面情緒:品牌宣傳、產業利好
? 負面情緒:爭議報道、事件沖突、政策打擊
可結合 pandas
分析負面情緒新聞數量趨勢與來源分布。
模塊 | 功能描述 |
---|---|
數據獲取層 | 調用 SerpAPI 獲取新聞數據(Python 腳本) |
數據處理層 | 分詞、聚類、情感分析 |
存儲層 | MongoDB、Elasticsearch、CSV 文件等 |
可視化層 | Streamlit、Grafana、Tableau 等前端展示 |
推送機制 | 郵件、Slack、Webhook 自動通知 |
[SerpAPI] ──? [爬蟲腳本] ──? [數據分析模塊] ──? [MongoDB]
│
└──? [Streamlit儀表盤]
└──? [郵件/Slack通知]
應用方向 | 使用效果 |
---|---|
內容編輯選題 | 自動生成當日或本周推薦話題 |
輿情監控與公關 | 識別負面新聞集中趨勢并快速響應 |
投資研究與資訊分析 | 追蹤特定行業或企業相關新聞密度與情感波動 |
自動新聞推薦系統 | 對用戶感興趣關鍵詞進行聚類與趨勢推送 |
參考 YouTube 上的 n8n + Google News Scraper 自動策劃內容 教程,以下是典型流程:
問題場景 | 建議策略 |
---|---|
API 請求頻率過快 | 加入 time.sleep() 限流,或使用緩存機制 |
返回新聞數量不足 | 拆分關鍵詞或提高 num 參數(建議 ≤ 100) |
關鍵詞聚類不準確 | 使用深度 Embedding(如 BERT + UMAP)代替 TF-IDF |
時間標簽模糊(如"4小時前") | 使用服務端統一轉換為 UTC 格式 |
通過結合 Google News API、關鍵詞提取、情感分析與趨勢聚類等技術,你可以構建:
無論你是內容編輯、數據分析師、產品經理還是開發者,Google News API 都是構建“信息優勢”的關鍵一環。