手动天气

该程序需要手动输入城市名

自动天气(不需要手动输入城市):https://www.cnblogs.com/Ctrl-cCtrl-v/p/12906084.html

 1 import urllib.request
 2 import gzip
 3 import json
 4 print('------天气查询------')
 5 def get_weather_data() :
 6     city_name = input('请输入要查询的城市名称:')
 7     url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
 8     url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
 9     #网址1只需要输入城市名,网址2需要输入城市代码
10     #print(url1)
11     weather_data = urllib.request.urlopen(url1).read()
12     #读取网页数据
13     weather_data = gzip.decompress(weather_data).decode('utf-8')
14     #解压网页数据
15     weather_dict = json.loads(weather_data)
16     #将json数据转换为dict数据
17     return weather_dict
18 
19 def show_weather(weather_data):
20     weather_dict = weather_data
21     #将json数据转换为dict数据
22     if weather_dict.get('desc') == 'invilad-citykey':
23         print('你输入的城市名有误,或者天气中心未收录你所在城市')
24     elif weather_dict.get('desc') =='OK':
25         forecast = weather_dict.get('data').get('forecast')
26         print('城市:',weather_dict.get('data').get('city'))
27         print('温度:',weather_dict.get('data').get('wendu')+'')
28         print('感冒:',weather_dict.get('data').get('ganmao'))
29         #print('风向:',forecast[0].get('fengxiang'))
30         print('风级:',forecast[0].get('fengli'))
31         print('高温:',forecast[0].get('high'))
32         print('低温:',forecast[0].get('low'))
33         print('天气:',forecast[0].get('type'))
34         print('日期:',forecast[0].get('date'))
35         print('*******************************')
36     
37         for i in range(1,5):
38             print('日期:',forecast[i].get('date'))
39             #print('风向:',forecast[i].get('fengxiang'))
40             print('风级:',forecast[i].get('fengli'))
41             print('高温:',forecast[i].get('high'))
42             print('低温:',forecast[i].get('low'))
43             print('天气:',forecast[i].get('type'))
44             print('--------------------------')
45     print('***********************************')
46 
47 while True:
48     show_weather(get_weather_data())

猜你喜欢

转载自www.cnblogs.com/Ctrl-cCtrl-v/p/12906077.html