Python智能天气信息

软件开发大郭
0 评论
/
19 阅读
/
1814 字
19 2022-12
分类:

核心功能 - 智能天气信息

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

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

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

实现代码

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)
    暂无数据