python学习之天气爬虫

 1 # -*- coding: utf-8 -*-
 2 
 3 import urllib.request
 4 
 5 import json
 6 import gzip
 7 
 8 cityname = input('请输入你想查询的城市:
')
 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') + '
' 
29                 + '日期:' + forecast[0].get('date') + '
' 
30                 + '温度:' + weather_dict.get('data').get('wendu') + '' 
31                 + '高温:' + forecast[0].get('high') + '' 
32                 + '低温: ' + forecast[0].get('low') + '' 
33                 + '风向:' + forecast[0].get('fengxiang') + '
' 
34                 + '风力:' + forecast[0].get('fengli') + '
' 
35                 + '天气:' + forecast[0].get('type') + '
' 
36                 + '感冒:' + weather_dict.get('data').get('ganmao') + '
'
37 
38     one_day = '日期:' + forecast[1].get('date') + '
' 
39               + '天气:' + forecast[1].get('type') + '
' 
40               + '高温:' + forecast[1].get('high') + '
' 
41               + '低温:' + forecast[1].get('low') + '
' 
42               + '风向:' + forecast[1].get('fengxiang') + '
' 
43               + '风力:' + forecast[1].get('fengli') + '
'
44 
45     two_day = '日期:' + forecast[2].get('date') + '
' 
46               + '天气:' + forecast[2].get('type') + '
' 
47               + '高温:' + forecast[2].get('high') + '
' 
48               + '低温:' + forecast[2].get('low') + '
' 
49               + '风向:' + forecast[2].get('fengxiang') + '
' 
50               + '风力:' + forecast[2].get('fengli') + '
'
51 
52     three_day = '日期:' + forecast[3].get('date') + '
' 
53                 + '天气:' + forecast[3].get('type') + '
' 
54                 + '高温:' + forecast[3].get('high') + '
' 
55                 + '低温:' + forecast[3].get('low') + '
' 
56                 + '风向:' + forecast[3].get('fengxiang') + '
' 
57                 + '风力:' + forecast[3].get('fengli') + '
'
58 
59     four_day = '日期:' + forecast[4].get('date') + '
' 
60                + '天气:' + forecast[4].get('type') + '
' 
61                + '高温:' + forecast[4].get('high') + '
' 
62                + '低温:' + forecast[4].get('low') + '
' 
63                + '风向:' + forecast[4].get('fengxiang') + '
' 
64                + '风力:' + forecast[4].get('fengli') + '
'
65 
66     print(one_day)
67     print(two_day)
68     print(three_day)
69     print(four_day)
原文地址:https://www.cnblogs.com/hfct/p/10978285.html