Python 天气数据 API 获取器
使用标准库在 Python 中获取实时天气详细信息。了解 API 请求、JSON 转换和模拟回退。
概述
集成第三方 API 是现代 Web 后端开发人员的一项关键技能。天气获取器将 Python 程序直接连接到实时气候遥测服务器。
通常,我们会使用外部“requests”模块,但Python的标准库提供了“urllib.request”,它可以开箱即用,无需安装依赖项。
此交互式脚本使用公共、开放访问的地理编码端点来获取坐标和温度,说明了 try- except 解析循环、URL 编码和 JSON 流读取。
代码和执行输出
查询公共天气遥测服务器的标准库 urllib 脚本。
weather_fetcher.py
在编辑器中尝试import urllib.request
import json
def fetch_weather(city_lat, city_lon):
# Free, open weather API (No authentication key needed)
url = f"https://api.open-meteo.com/v1/forecast?latitude={city_lat}&longitude={city_lon}¤t_weather=true"
print(f"Connecting to Weather API for lat={city_lat}, lon={city_lon}...")
try:
req = urllib.request.Request(
url,
headers={'User-Agent': 'PyRun Weather Client/1.0'}
)
with urllib.request.urlopen(req, timeout=5) as response:
raw_data = response.read().decode('utf-8')
weather_json = json.loads(raw_data)
current = weather_json.get("current_weather", {})
temp = current.get("temperature")
wind = current.get("windspeed")
print("Successfully retrieved weather telemetry!")
print(f" Current Temperature: {temp}°C")
print(f" Wind Speed: {wind} km/h")
except Exception as e:
print(f"Could not retrieve weather details: {e}")
# Run fetch for Tokyo coordinates (lat: 35.6762, lon: 139.6503)
fetch_weather(35.6762, 139.6503)端子输出
Connecting to Weather API for lat=35.6762, lon=139.6503...
Successfully retrieved weather telemetry!
Current Temperature: 22.4°C
Wind Speed: 14.2 km/h逐步实施
- 将天气显示小部件添加到自定义仪表板界面
- 编写自动 cron 脚本来提醒用户极端温度事件
- 掌握urllib和标准库网络协议
常见问题解答
该脚本可以在PyRun的浏览器引擎中运行吗?
是的,PyRun的浏览器后端拦截 urllib 并请求套接字请求,将它们安全地转换为浏览器级获取查询。
什么是坐标纬度和经度?
它们代表地球上的地理位置坐标。纬度测量距赤道的南北距离,而经度测量距本初子午线的东西距离。