我的项目3:使用 Python + Streamlit 构建天气应用
发布: (2025年12月1日 GMT+8 06:26)
3 min read
原文: Dev.to
Source: Dev.to
1. 项目概述
- 输入城市名称
- 使用 wttr.in 获取实时天气
- 查看温度、天气状况、湿度
- 可作为控制台脚本 (
weather.py) 或 Streamlit 网页 UI (weather_streamlit.py) 使用
简洁、实用,非常适合 Python 练手。
2. 使用的 API:wttr.in
选择 wttr.in 的原因是它:
- 无需注册
- 能轻松返回 JSON
- 适合快速项目
3. 控制台版本 (weather.py)
主要特性
- 使用
requests库请求天气 - 显示温度、天气描述和湿度
- 优雅地处理错误
代码
import requests
city = input("Enter city name: ")
url = f"https://wttr.in/{city}?format=j1"
response = requests.get(url)
if response.status_code != 200:
print("Error fetching weather data.")
exit()
data = response.json()
current = data["current_condition"][0]
print("=== Weather Report ===")
print("City:", city)
print("Temperature:", current["temp_C"], "°C")
print("Weather:", current["weatherDesc"][0]["value"])
print("Humidity:", current["humidity"], "%")
4. Streamlit 网页版本 (weather_streamlit.py)
为什么选 Streamlit?
- 干净的网页 UI
- 用户友好的城市输入框
- 清晰的错误提示
- 美观的天气数据展示
代码
import streamlit as st
import requests
st.title("🌤️ Sabin's Weather App")
city = st.text_input("Enter city name:", "Chur")
if st.button("Check Weather"):
url = f"https://wttr.in/{city}?format=j1"
response = requests.get(url)
if response.status_code != 200:
st.error("Error fetching weather data.")
else:
data = response.json()
current = data["current_condition"][0]
temp = current["temp_C"]
desc = current["weatherDesc"][0]["value"]
humidity = current["humidity"]
st.subheader(f"Weather in {city}")
st.write(f"🌡 Temperature: **{temp}°C**", unsafe_allow_html=True)
st.write(f"☁ Condition: **{desc}**", unsafe_allow_html=True)
st.write(f"💧 Humidity: **{humidity}%**", unsafe_allow_html=True)
5. 如何运行
控制台版本
python3 weather.py
Streamlit 版本
pip install streamlit
streamlit run weather_streamlit.py
Streamlit 会自动打开浏览器窗口显示网页 UI。
6. 我的收获
- 使用
requests进行 API 请求 - 解析 JSON 响应
- 用 Streamlit 构建交互式 UI
- 处理网络响应的错误
- 将控制台脚本转换为网页应用
7. 未来改进方向
- 添加天气图标
- 显示小时和周预报
- 支持多语言
- 添加背景主题(晴天、阴天、雨天)
- 支持保存常用城市