
构建基于Claude MCP的天气查询智能体 | 实战落地示例
在数字信息爆炸的时代,掌握第一手新闻数据已经成为运营、舆情分析、金融监控、内容创作等多个行业的核心需求。而 Google News 因其权威性与多语种覆盖,成为开发者获取全球新闻的理想源头。
通过 Google News API 或其替代方案,开发者可以轻松:
目前 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 是目前最稳定、最易用的开发者解决方案。
通过本文你已掌握: