手把手教你用Python调用免费天气API,5分钟搞定城市代码查询与数据解析

📅 2026/7/5 11:44:29 👁️ 阅读次数 📝 编程学习
手把手教你用Python调用免费天气API,5分钟搞定城市代码查询与数据解析

Python实战:5分钟快速集成天气API与智能城市代码查询系统

最近在开发一个社区服务小程序时,需要添加实时天气功能模块。原本以为调用个API就能轻松搞定,结果发现光是处理城市代码匹配就耗费了大半天时间。相信很多开发者都遇到过类似困扰——面对陌生的API接口文档和冗长的城市代码列表,不知从何下手。本文将分享一套经过实战检验的解决方案,让你在5分钟内完成从城市名查询到天气数据获取的全流程实现。

1. 环境准备与基础配置

在开始编码前,我们需要确保开发环境就绪。推荐使用Python 3.6+版本,这个项目只需要安装最基本的requests库即可:

pip install requests

为了后续开发方便,建议新建一个weather_api.py文件作为主程序文件。这个文件将包含我们所有的功能实现。先创建一个基础类结构:

import requests import json class WeatherAPI: def __init__(self): self.base_url = "http://t.weather.itboy.net/api/weather/city/" self.city_code_map = {} # 用于存储城市代码映射关系 def get_weather(self, city_name): pass

关键点说明

  • 使用类封装可以更好地组织代码
  • base_url是API的基础地址
  • city_code_map将用于缓存城市代码查询结果

2. 智能城市代码查询系统

原始的城市代码列表过于庞大,直接硬编码在程序中既不优雅也难以维护。我们可以设计一个智能查询系统,通过以下步骤实现:

2.1 构建城市代码数据库

首先创建一个独立的city_codes.json文件存储城市代码数据。这样做的优势是:

  • 数据与代码分离,便于维护更新
  • 可以随时扩展新的城市数据
  • 减少内存占用(按需加载)

文件结构示例:

{ "北京": { "北京": "101010100", "海淀": "101010200", "朝阳": "101010300" }, "上海": { "上海": "101020100", "闵行": "101020200", "宝山": "101020300" } }

2.2 实现智能查询功能

在WeatherAPI类中添加以下方法:

def load_city_codes(self, filepath='city_codes.json'): with open(filepath, 'r', encoding='utf-8') as f: self.city_code_map = json.load(f) def find_city_code(self, city_name): for province, cities in self.city_code_map.items(): if city_name in cities: return cities[city_name] raise ValueError(f"未找到城市'{city_name}'对应的代码")

优化技巧

  • 添加模糊匹配功能,处理用户输入误差
  • 实现缓存机制,避免重复加载文件
  • 支持省市区三级查询

3. 完整API调用与数据处理

现在我们可以实现完整的天气查询功能了。更新get_weather方法:

def get_weather(self, city_name): try: city_code = self.find_city_code(city_name) response = requests.get(f"{self.base_url}{city_code}") response.raise_for_status() return self._parse_weather_data(response.json()) except Exception as e: return {"error": str(e)} def _parse_weather_data(self, data): return { "city": data["cityInfo"]["city"], "update_time": data["time"], "weather": data["data"]["forecast"][0]["type"], "temperature": f"{data['data']['forecast'][0]['low']} ~ {data['data']['forecast'][0]['high']}", "humidity": data["data"]["shidu"], "air_quality": data["data"]["quality"] }

错误处理要点

  • 网络请求超时设置
  • API响应状态检查
  • JSON解析异常捕获
  • 数据字段缺失处理

4. 实战应用与性能优化

4.1 实际调用示例

创建一个简单的命令行交互界面:

if __name__ == "__main__": weather_api = WeatherAPI() weather_api.load_city_codes() while True: city = input("请输入查询城市名称(输入q退出): ") if city.lower() == 'q': break result = weather_api.get_weather(city) if "error" in result: print(f"查询失败: {result['error']}") else: print(f"\n{city}天气信息:") for key, value in result.items(): print(f"{key}: {value}") print()

4.2 性能优化策略

  1. 缓存机制
from functools import lru_cache @lru_cache(maxsize=100) def get_weather(self, city_name): # 原有实现
  1. 异步请求
import aiohttp import asyncio async def async_get_weather(self, city_name): async with aiohttp.ClientSession() as session: async with session.get(f"{self.base_url}{city_code}") as response: data = await response.json() return self._parse_weather_data(data)
  1. 批量查询支持
def batch_get_weather(self, city_list): with ThreadPoolExecutor() as executor: results = list(executor.map(self.get_weather, city_list)) return results

5. 扩展功能与异常场景处理

实际项目中,我们还需要考虑更多边界情况:

5.1 城市别名支持

很多城市有常用别名(如"帝都"指北京),可以通过扩展city_codes.json实现:

{ "北京": { "北京": "101010100", "帝都": "101010100", "京城": "101010100" } }

5.2 天气数据可视化

使用matplotlib添加简单的数据可视化:

def plot_temperature_trend(self, city_name, days=7): weather_data = self.get_week_forecast(city_name) dates = [d['date'] for d in weather_data] highs = [int(d['high'].split(' ')[1]) for d in weather_data] lows = [int(d['low'].split(' ')[1]) for d in weather_data] plt.plot(dates, highs, label='最高气温') plt.plot(dates, lows, label='最低气温') plt.fill_between(dates, highs, lows, alpha=0.1) plt.title(f"{city_name}未来{days}天气温趋势") plt.legend() plt.show()

5.3 常见错误代码处理

ERROR_MAP = { 404: "城市代码不存在", 500: "服务器内部错误", 502: "网关错误", 503: "服务不可用" } def get_weather(self, city_name): try: city_code = self.find_city_code(city_name) response = requests.get(f"{self.base_url}{city_code}", timeout=5) if response.status_code != 200: error_msg = ERROR_MAP.get(response.status_code, "未知错误") return {"error": f"API请求失败: {error_msg}"} return self._parse_weather_data(response.json()) except requests.exceptions.Timeout: return {"error": "请求超时,请稍后重试"} except requests.exceptions.RequestException as e: return {"error": f"网络请求异常: {str(e)}"}

在最近的一个电商项目中,这套天气查询系统帮助我们在用户地址页面集成了实时天气展示功能。最初版本没有城市别名支持,导致部分用户输入"榕城"(福州别称)时查询失败。后来通过扩展城市代码数据库,增加了常见城市别名的映射,用户体验得到了显著提升。