python学习之天气爬虫

 1 # -*- coding: utf-8 -*-
 2 
 3 import urllib.request
 4 
 5 import json
 6 import gzip
 7 
 8 cityname = input('请输入你想查询的城市:\n')
 9 
10 # 访问的url,其中urllib.parse.quote是将城市名转换为url的组件
11 url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(cityname)
12 
13 # 发出请求并读取到weather_data
14 weather_data = urllib.request.urlopen(url).read()
15 
16 # 以utf-8的编码方式解压数据
17 weather_data = gzip.decompress(weather_data).decode('utf-8')
18 
19 # 将json数据转化为dict数据
20 weather_dict = json.loads(weather_data)
21 
22 if weather_dict.get('desc') == 'invilad-citykey':
23     print("输入的城市名错误")
24 
25 elif weather_dict.get('desc') == 'OK':
26     forecast = weather_dict.get('data').get('forecast')
27 
28     startoday = '城市:' + weather_dict.get('data').get('city') + '\n' \
29                 + '日期:' + forecast[0].get('date') + '\n' \
30                 + '温度:' + weather_dict.get('data').get('wendu') + '℃\n' \
31                 + '高温:' + forecast[0].get('high') + '℃\n' \
32                 + '低温: ' + forecast[0].get('low') + '℃\n' \
33                 + '风向:' + forecast[0].get('fengxiang') + '\n' \
34                 + '风力:' + forecast[0].get('fengli') + '\n' \
35                 + '天气:' + forecast[0].get('type') + '\n' \
36                 + '感冒:' + weather_dict.get('data').get('ganmao') + '\n'
37 
38     one_day = '日期:' + forecast[1].get('date') + '\n' \
39               + '天气:' + forecast[1].get('type') + '\n' \
40               + '高温:' + forecast[1].get('high') + '\n' \
41               + '低温:' + forecast[1].get('low') + '\n' \
42               + '风向:' + forecast[1].get('fengxiang') + '\n' \
43               + '风力:' + forecast[1].get('fengli') + '\n'
44 
45     two_day = '日期:' + forecast[2].get('date') + '\n' \
46               + '天气:' + forecast[2].get('type') + '\n' \
47               + '高温:' + forecast[2].get('high') + '\n' \
48               + '低温:' + forecast[2].get('low') + '\n' \
49               + '风向:' + forecast[2].get('fengxiang') + '\n' \
50               + '风力:' + forecast[2].get('fengli') + '\n'
51 
52     three_day = '日期:' + forecast[3].get('date') + '\n' \
53                 + '天气:' + forecast[3].get('type') + '\n' \
54                 + '高温:' + forecast[3].get('high') + '\n' \
55                 + '低温:' + forecast[3].get('low') + '\n' \
56                 + '风向:' + forecast[3].get('fengxiang') + '\n' \
57                 + '风力:' + forecast[3].get('fengli') + '\n'
58 
59     four_day = '日期:' + forecast[4].get('date') + '\n' \
60                + '天气:' + forecast[4].get('type') + '\n' \
61                + '高温:' + forecast[4].get('high') + '\n' \
62                + '低温:' + forecast[4].get('low') + '\n' \
63                + '风向:' + forecast[4].get('fengxiang') + '\n' \
64                + '风力:' + forecast[4].get('fengli') + '\n'
65 
66     print(one_day)
67     print(two_day)
68     print(three_day)
69     print(four_day)

 

posted @ 2019-06-05 10:46  疾风不弃  阅读(561)  评论(0编辑  收藏  举报