0Pricing
Learn AI with Python · 课时

使用公共数据 API

通过 OpenWeatherMap、Wikipedia 和政府公共 API 学习实际数据采集

使用公共数据 API 是 CoddyKit 上的免费 Learn AI with Python 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Learn AI with Python 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Learn AI with Python 课程共包含 4 节课。

使用公共接口进行练习

学习数据采集的最佳方式是调用真实的接口。本课将使用以下三个易于上手的接口:

  • JSONPlaceholder — 用于练习的虚拟 REST 接口,无需密钥
  • OpenWeatherMap — 提供真实天气数据,需要免费的接口密钥
  • 维基百科接口 — 提供文章内容和搜索功能

使用 JSONPlaceholder 进行练习

JSONPlaceholder 无需身份验证即可提供虚拟的帖子、用户和评论。它非常适合用来测试您的请求和解析代码。

import requests

resp = requests.get("https://jsonplaceholder.typicode.com/posts", timeout=10)
resp.raise_for_status()
posts = resp.json()
print(len(posts), "posts")
print(posts[0]["title"])

从响应到 DataFrame 的工作流程

标准工作流程是:获取 JSON,然后直接将其加载到 DataFrame 中进行分析。

import pandas as pd

posts = requests.get("https://jsonplaceholder.typicode.com/posts", timeout=10).json()
df = pd.DataFrame(posts)
print(df.head())
print(df["userId"].value_counts())

OpenWeatherMap — 获取密钥

OpenWeatherMap 要求通过 appid 参数传入免费的接口密钥。请不要将密钥写入代码,而应从环境变量中读取。

import os

API_KEY = os.environ["OWM_API_KEY"]   # set OWM_API_KEY in your shell

OpenWeatherMap — 查询参数

当前天气接口接受 q(城市)、appid(密钥)和 units(公制/英制)参数。

import requests, os

params = {
    "q": "Istanbul",
    "appid": os.environ["OWM_API_KEY"],
    "units": "metric",
}
resp = requests.get("https://api.openweathermap.org/data/2.5/weather", params=params, timeout=10)
resp.raise_for_status()
data = resp.json()

提取嵌套的 JSON 字段

真实的接口响应通常具有很深的嵌套结构。您可以通过连续访问键逐层深入,并对可能缺失的字段使用带默认值的 .get()。

temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
desc = data["weather"][0]["description"]
print(f"{temp} C, {humidity}% humidity, {desc}")

采集多个城市的天气

遍历城市列表,将您关注的字段展平为字典列表,然后构建 DataFrame。

cities = ["Istanbul", "London", "Tokyo"]
rows = []
for c in cities:
    p = {"q": c, "appid": os.environ["OWM_API_KEY"], "units": "metric"}
    d = requests.get("https://api.openweathermap.org/data/2.5/weather", params=p, timeout=10).json()
    rows.append({"city": c, "temp": d["main"]["temp"], "desc": d["weather"][0]["description"]})
import pandas as pd
df = pd.DataFrame(rows)

维基百科接口

维基百科接口提供搜索和文章内容。它要求传入 action 和 format=json,并添加描述性的 User-Agent 标头。

params = {
    "action": "query",
    "list": "search",
    "srsearch": "machine learning",
    "format": "json",
}
headers = {"User-Agent": "data-collector/1.0 (you@example.com)"}
resp = requests.get("https://en.wikipedia.org/w/api.php", params=params, headers=headers, timeout=10)
results = resp.json()["query"]["search"]

获取文章摘要

使用 prop=extracts 和 exintro=True 获取文章的引言段落,这对于构建文本数据集很有帮助。

params = {
    "action": "query",
    "prop": "extracts",
    "exintro": True,
    "explaintext": True,
    "titles": "Artificial intelligence",
    "format": "json",
}
resp = requests.get("https://en.wikipedia.org/w/api.php", params=params, timeout=10)
pages = resp.json()["query"]["pages"]
for pid, page in pages.items():
    print(page["extract"][:300])

阅读接口文档

每个接口都有所不同。开始编写代码前,请阅读文档,了解以下内容:基础网址、必需参数、身份验证方式、响应结构和速率限制。

先以交互方式测试一个请求,检查 resp.json(),然后根据真实结构构建循环。

做一个合格的接口使用者

公共接口是由大家共享的资源。请遵守以下规范:

  • 发送可标识您身份的 User-Agent
  • 缓存结果,避免重复获取相同数据
  • 在请求之间暂停,并遵守速率限制
  • 阅读并遵守各个接口的使用条款

快速检查:练习接口

您希望在不注册接口密钥的情况下,测试请求和解析代码。

回顾:公共数据接口

您已经练习了从真实接口采集数据:

  • 使用 JSONPlaceholder 进行无需身份验证的练习
  • 使用 OpenWeatherMap,传入 q、appid、units 参数,并从环境中读取密钥
  • 使用维基百科接口进行搜索并获取文章摘要
  • 掌握从获取数据到加载进 DataFrame 的工作流程,以及如何逐层访问嵌套 JSON
  • 养成合格接口使用者的习惯:设置 User-Agent、缓存数据、遵守速率限制和使用条款

数据采集部分到此完成。下一步:用于文本人工智能的正则表达式。

常见问题解答

「使用公共数据 API」课时是免费的吗?

是的 — 「使用公共数据 API」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Learn AI with Python 课程的其余内容,请升级到 CoddyKit PRO。 Learn AI with Python 课程共包含 4 节课。

「使用公共数据 API」这节课中我会学到什么?

通过 OpenWeatherMap、Wikipedia 和政府公共 API 学习实际数据采集 你通过在浏览器中直接运行的动手代码来练习 Learn AI with Python,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Learn AI with Python 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Learn AI with Python 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用公共数据 API」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Learn AI with Python 课中编写并运行代码吗?

能。每节 Learn AI with Python 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 数据采集的 REST API 基础
  2. 分页与大型数据集采集
  3. 高效存储采集的数据
  4. 使用公共数据 API
← 返回 Learn AI with Python