核心功能 - 智能天气信息

国家气象局网站提供获取天气预报的 API,直接返回 json 格式的天气数据。所以只需要从 json 里取出对应的字段就可以了。

下面是指定城市(县、区)天气的网址,直接打开网址,就会返回对应城市的天气数据。比如:

http://www.weather.com.cn/data/cityinfo/101021200.html 上海徐汇区对应的天气网址。

实现代码

  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


import requests 


import json 


import logging as log 


 


def get_weather_wind(url): 


    r = requests.get(url) 


    if r.status_code != 200: 


        log.error("Can't get weather data!") 


    info = json.loads(r.content.decode()) 


 


    # get wind data 


    data = info['weatherinfo'] 


    WD = data['WD'] 


    WS = data['WS'] 


    return "{}({})".format(WD, WS) 


 


def get_weather_city(url): 


    # open url and get return data 


    r = requests.get(url) 


    if r.status_code != 200: 


        log.error("Can't get weather data!") 


 


    # convert string to json 


    info = json.loads(r.content.decode()) 


 


    # get useful data 


    data = info['weatherinfo'] 


    city = data['city'] 


    temp1 = data['temp1'] 


    temp2 = data['temp2'] 


    weather = data['weather'] 


    return "{} {} {}~{}".format(city, weather, temp1, temp2) 


 


if __name__ == '__main__': 


    msg = """**天气提醒**:   


 


{} {}   


{} {}   


 


来源: 国家气象局 


""".format( 


    get_weather_city('http://www.weather.com.cn/data/cityinfo/101021200.html'), 


    get_weather_wind('http://www.weather.com.cn/data/sk/101021200.html'), 


    get_weather_city('http://www.weather.com.cn/data/cityinfo/101020900.html'), 


    get_weather_wind('http://www.weather.com.cn/data/sk/101020900.html') 


) 


    print(msg)