本文目录导读:

Python + 第三方API(最常用)
使用 OpenWeatherMap(免费)
import requests
import json
def get_weather(city="北京", api_key="你的API密钥"):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&lang=zh_cn&units=metric"
try:
response = requests.get(url)
data = response.json()
if data.get("cod") == 200:
weather = {
"城市": data["name"],
"温度": f"{data['main']['temp']}°C",
"天气": data["weather"][0]["description"],
"湿度": f"{data['main']['humidity']}%",
"风速": f"{data['wind']['speed']}m/s"
}
return weather
else:
return f"错误: {data.get('message', '未知错误')}"
except Exception as e:
return f"请求失败: {str(e)}"
# 使用示例
if __name__ == "__main__":
result = get_weather("北京")
print(json.dumps(result, ensure_ascii=False, indent=2))
使用和风天气(国内更快)
import requests
def get_weather_heweather(city_id="101010100", api_key="你的API密钥"):
url = f"https://devapi.qweather.com/v7/weather/now?location={city_id}&key={api_key}"
response = requests.get(url)
data = response.json()
if data["code"] == "200":
now = data["now"]
return {
"温度": f"{now['temp']}°C",
"体感温度": f"{now['feelsLike']}°C",
"天气": now["text"],
"风向": now["windDir"],
"风力": now["windScale"] + "级"
}
else:
return f"错误: {data['code']}"
Bash/Shell 脚本(轻量级)
#!/bin/bash # 使用 wttr.in 免费API # 获取天气信息 weather=$(curl -s "wttr.in/北京?format=3&lang=zh" 2>/dev/null) # 格式化输出 echo "=== 天气预报 ===" echo "$weather" # 获取详细天气 echo "" echo "=== 详细天气 ===" curl -s "wttr.in/北京?lang=zh&m" 2>/dev/null | head -20
使用方式:
chmod +x weather.sh ./weather.sh
JavaScript/Node.js
// 使用 axios 获取天气
const axios = require('axios');
async function getWeather(city = '北京') {
try {
const response = await axios.get('http://api.openweathermap.org/data/2.5/weather', {
params: {
q: city,
appid: '你的API密钥',
lang: 'zh_cn',
units: 'metric'
}
});
const data = response.data;
console.log(`
城市: ${data.name}
温度: ${data.main.temp}°C
天气: ${data.weather[0].description}
湿度: ${data.main.humidity}%
风速: ${data.wind.speed}m/s
`);
return data;
} catch (error) {
console.error('获取天气失败:', error.message);
}
}
// 调用函数
getWeather('上海');
命令行直接获取(最简单)
# 方法1:使用 curl curl "wttr.in/北京?lang=zh&m" # 方法2:使用 wget wget -O- "wttr.in/上海?lang=zh&m" # 方法3:指定格式(单行显示) curl "wttr.in/广州?format=%l:+%c+%t+%w+%h&lang=zh" # 方法4:获取某个城市未来3天天气 curl "wttr.in/深圳?lang=zh&m&3"
完整示例:定时获取天气并发送通知
#!/usr/bin/env python3
import subprocess
import platform
def get_weather_cli(city="北京"):
"""使用 wttr.in 获取天气"""
cmd = f'curl -s "wttr.in/{city}?lang=zh&format=3"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout.strip()
def send_notification(title, message):
"""跨平台发送通知"""
system = platform.system()
if system == "Darwin": # macOS
subprocess.run(["osascript", "-e", f'display notification "{message}" with title "{title}"'])
elif system == "Linux":
subprocess.run(["notify-send", title, message])
elif system == "Windows":
subprocess.run(["powershell", "-Command",
f'[System.Windows.Forms.MessageBox]::Show("{message}", "{title}")'])
# 主程序
if __name__ == "__main__":
weather_info = get_weather_cli("北京")
print(f"当前天气: {weather_info}")
# 发送到桌面通知
send_notification("天气预报", weather_info)
需要准备的东西:
-
注册API密钥(如果使用正式API):
- OpenWeatherMap: https://openweathermap.org/api
- 和风天气: https://dev.qweather.com/
- 聚合数据: https://www.juhe.cn/docs/api/id/39
-
安装依赖:
pip install requests # 或 npm install axios
免费方案提示:
- wttr.in:完全免费,无需注册,支持中文,适合快速使用
- OpenWeatherMap:免费版每天2000次请求,够个人使用
- 和风天气:个人版免费,国内速度更快
推荐:如果你只是临时用,直接使用 wttr.in 最简单;如果需要集成到自己的项目,建议用 OpenWeatherMap 或和风天气的API。
需要我详细解释某个方法,或者帮你写特定功能的脚本吗?