1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
| import requests
from bs4 import BeautifulSoup
import json
import time
# 设置请求头,模拟浏览器访问
myHeader = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
}
def getProvCityInfo():
"""获取省份城市信息"""
try:
url = 'https://j.i8tq.com/weather2020/search/city.js'
r = requests.get(url, headers=myHeader, timeout=10)
r.raise_for_status() # 检查请求是否成功
content = r.content.decode('utf-8')
cityData = content[len('var city_data = '):-1]
cityData = json.loads(cityData)
cityInfo = {}
for prov in cityData.keys():
for city_key in cityData[prov].keys():
for city in cityData[prov][city_key].keys():
id = cityData[prov][city_key][city]['AREAID']
name = cityData[prov][city_key][city]['NAMECN']
cityInfo[name] = str(id)
return cityInfo
except requests.exceptions.RequestException as e:
print(f"网络请求错误: {e}")
return {}
except json.JSONDecodeError as e:
print(f"数据解析错误: {e}")
return {}
except Exception as e:
print(f"未知错误: {e}")
return {}
def getCityInfo():
"""获取城市信息"""
print("=" * 50)
print("天气查询系统".center(46))
print("=" * 50)
while True:
cityInfo = getProvCityInfo()
if not cityInfo:
print("无法获取城市列表,请检查网络连接!")
time.sleep(2)
continue
print("\n支持的查询格式:")
print("1. 直辖市:北京、上海、天津、重庆")
print("2. 省会城市:广州、南京、杭州等")
print("3. 地级市:苏州、深圳、青岛等")
print("4. 县级市/区:请确保输入完整名称")
print("-" * 50)
cityName = input("请输入待查询城市名称(输入'退出'结束查询):").strip()
if cityName.lower() in ['退出', 'exit', 'quit']:
print("感谢使用天气查询系统,再见!")
exit()
if not cityName:
print("城市名称不能为空!")
continue
cityCode = cityInfo.get(cityName, 0)
if cityCode == 0:
print(f"⚠️ 您输入的'{cityName}'不存在!")
print("提示:请检查城市名称是否完整,或尝试使用省级城市名称")
continue
else:
print(f"✓ 正在查询{cityName}的天气...")
break
return cityName, cityCode
def getWeatherInfo(cityCode):
"""获取天气信息"""
try:
website = 'https://www.weather.com.cn/weather1d/' + cityCode + '.shtml'
r = requests.get(website, headers=myHeader, timeout=10)
r.raise_for_status()
html = r.content.decode('utf-8')
soup = BeautifulSoup(html, "html.parser")
# 获取天气状况
weather_elem = soup.find("p", class_="wea")
if not weather_elem:
return None, "天气信息获取失败"
weather = weather_elem.text.strip()
# 获取气温
temp_elem = soup.find("p", class_="tem")
if not temp_elem:
return None, "气温信息获取失败"
temp = temp_elem.get_text(strip=True)
# 获取天空状况
sky_elem = soup.find("div", class_="sky")
if sky_elem and sky_elem.find("span"):
sky = sky_elem.find("span").get_text(strip=True)
else:
sky = ""
# 获取日出日落时间
sunUp_elem = soup.find('p', class_="sun sunUp")
sunDown_elem = soup.find('p', class_="sun sunDown")
sunUp = sunUp_elem.text.strip() if sunUp_elem else "未知"
sunDown = sunDown_elem.text.strip() if sunDown_elem else "未知"
# 获取风力信息(可选)
wind_elem = soup.find("p", class_="win")
wind = wind_elem.text.strip() if wind_elem else ""
return {
"weather": weather,
"temp": temp,
"sky": sky,
"sunUp": sunUp,
"sunDown": sunDown,
"wind": wind
}, None
except requests.exceptions.RequestException as e:
return None, f"网络请求失败: {e}"
except Exception as e:
return None, f"获取天气信息时出错: {e}"
def displayWeatherInfo(cityName, weather_data):
"""显示天气信息"""
print("\n" + "=" * 50)
print(f"🏙️ {cityName} 天气信息".center(46))
print("=" * 50)
# 显示温度符号(放在后面)
temp_display = weather_data["temp"]
if "°C" in temp_display:
temp_value = temp_display.replace("°C", "")
try:
temp_num = int(temp_value.replace("-", "").replace("+", ""))
if "-" in temp_value:
temp_display = f"{temp_display} ❄️"
elif temp_num >= 30:
temp_display = f"{temp_display} 🔥"
elif temp_num >= 20:
temp_display = f"{temp_display} 😊"
except:
pass
# 显示天气状况符号
weather_display = weather_data["weather"]
if "晴" in weather_display:
weather_display = f"{weather_display} ☀️"
elif "多云" in weather_display:
weather_display = f"{weather_display} ⛅"
elif "阴" in weather_display or "云" in weather_display:
weather_display = f"{weather_display} ☁️"
elif "雨" in weather_display:
weather_display = f"{weather_display} 🌧️"
elif "雪" in weather_display:
weather_display = f"{weather_display} ❄️"
elif "雾" in weather_display or "霾" in weather_display:
weather_display = f"{weather_display} 🌫️"
print(f"📊 天气状况: {weather_display}")
print(f"🌡️ 当前气温: {temp_display}")
if weather_data["wind"]:
print(f"💨 风力风向: {weather_data['wind']}")
if weather_data["sky"]:
print(f"🌌 天空状况: {weather_data['sky']}")
print(f"🌅 日出时间: {weather_data['sunUp']}")
print(f"🌇 日落时间: {weather_data['sunDown']}")
# 显示当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"🕐 更新时间: {current_time}")
print("=" * 50)
def main():
"""主函数"""
while True:
try:
cityName, cityCode = getCityInfo()
weather_data, error = getWeatherInfo(cityCode)
if error:
print(f"\n❌ {error}")
print("请稍后重试或尝试其他城市。")
time.sleep(2)
continue
displayWeatherInfo(cityName, weather_data)
# 询问是否继续查询
print("\n是否继续查询其他城市天气?")
choice = input("输入 'y' 继续,其他任意键退出:").strip().lower()
if choice not in ['y', 'yes', '是', '继续']:
print("\n感谢使用天气查询系统,再见!")
break
except KeyboardInterrupt:
print("\n\n检测到中断操作,程序退出。")
break
except Exception as e:
print(f"\n程序运行异常: {e}")
print("请稍后重试...")
time.sleep(2)
if __name__ == "__main__":
main()
|