直接调用OpenWeatherMap公开API最简单可行,需注册获取API key;用requests发请求并检查status_code,解析JSON时注意weather[0]和main["temp"]字段;实时展示靠定时轮询+\r覆盖刷新,务必设timeout和异常处理。

直接调用公开天气 API(比如 OpenWeatherMap)是最简单可行的方式,不需要爬虫、不涉及反爬、响应快且数据结构稳定。关键前提是:你得先注册获取 API key,否则所有请求都会返回 401 Unauthorized。
怎么选 API 和注册 key?
推荐用 OpenWeatherMap 的免费版(1000 次/天,足够调试和小工具使用)。访问 https://openweathermap.org/api,点击 Sign Up,邮箱验证后在 API keys 页面就能看到一串以 appid= 开头的字符串——这就是你要保管好的 API key。
注意:weather 接口返回当前天气,forecast 返回 5 天每 3 小时预报;新手别一上来就用 forecast,字段多、嵌套深,容易解析出错。
- 城市名查询用
https://www.php.cn/link/1b75989164e8c45c9e64bc98df117ce3?q={city}&appid={key} - 经纬度查询更准(避免同名城市),用
lat/lon参数代替q - 返回默认是 Kelvin 温度,加
&units=metric才是摄氏度
怎么用 requests 获取并解析 JSON?
requests 是最轻量、最不容易出错的选择。别用 urllib 手动拼接、解码、异常处理——徒增复杂度。
立即学习“Python免费学习笔记(深入)”;
核心逻辑就三步:发请求 → 检查状态码 → 提取字段。常见错误是忽略 response.status_code != 200,结果程序卡住或报 KeyError。
import requests
<p>url = "<a href="https://www.php.cn/link/1b75989164e8c45c9e64bc98df117ce3">https://www.php.cn/link/1b75989164e8c45c9e64bc98df117ce3</a>"
params = {
"q": "Shanghai",
"appid": "your_api_key_here",
"units": "metric"
}
resp = requests.get(url, params=params)
if resp.status_code != 200:
print(f"API error: {resp.status_code} - {resp.text}")
exit()</p><p>data = resp.json()
temp = data["main"]["temp"]
desc = data["weather"][0]["description"]
print(f"上海:{temp}°C,{desc}")- 务必检查
resp.status_code,404 表示城市名拼错,401 表示 key 错或没填 -
data["weather"][0]是个列表,永远取第一个元素,别漏掉[0] - 温度字段是
data["main"]["temp"],不是data["temperature"]或data["temp"]
怎么做到“实时展示”?
所谓实时,其实是定期轮询(比如每 30 秒请求一次),不是 WebSocket 推送。用 time.sleep() 控制间隔,用 while True: 循环,但必须加异常捕获,否则网络抖动或 API 限流会让程序崩溃退出。
控制台刷新效果靠 \r 实现,比清屏(os.system('cls') 或 'clear')更轻量、跨平台兼容性更好。
import time
import requests
<p>def fetch_weather(city, key):
url = "<a href="https://www.php.cn/link/1b75989164e8c45c9e64bc98df117ce3">https://www.php.cn/link/1b75989164e8c45c9e64bc98df117ce3</a>"
params = {"q": city, "appid": key, "units": "metric"}
try:
r = requests.get(url, params=params, timeout=5)
if r.status_code == 200:
d = r.json()
return f"{d['name']}:{d['main']['temp']:.1f}°C,{d['weather'][0]['description']}"
except Exception as e:
return f"获取失败:{e}"
return "未知错误"</p><p>key = "your_api_key_here"
while True:
line = fetch_weather("Beijing", key)
print(f"\r{line}", end="", flush=True)
time.sleep(30)- 超时必须设
timeout=5,否则 DNS 失败或服务器无响应会卡死 60+ 秒 - 打印用
end=""+flush=True配合\r,才能覆盖上一行,而不是不断换行刷屏 - 别把
key硬编码进脚本,改用环境变量os.getenv("OWM_KEY")更安全
真正难的不是请求本身,而是错误路径的覆盖:网络中断、API 限流、城市名变更、JSON 字段临时调整……这些不会在教程里写,但上线跑两小时后大概率遇到。建议第一次运行时,先手动 curl 测试接口是否返回预期结构,再写解析逻辑。


















