获取城市天气

通过调用天气接口,查询城市天气情况

天气接口地址:http://wthrcdn.etouch.cn/weather_mini?city={cityName}

如查询广东省珠海市天气,直接打开浏览器,输入:http://wthrcdn.etouch.cn/weather_mini?city=珠海市

查询结果入下:

浏览器查询珠海市天气


根据python调用上述接口获取城市天气,具体如下:

# -*- coding=utf-8 -*-import timeimport requestsfrom pprint import pprintdef get_weather_today(cityName):    try:        global city, wendu, month, forecast  # 全局变量        global date, type, high, low, fengxiang, fengli  # 全局变量        url = f'http://wthrcdn.etouch.cn/weather_mini?city={cityName}'        response = requests.get(url)        dict_weather = response.json()        # pprint(dict_weather)  # 打印获取的城市天气信息        if dict_weather['desc'] == 'OK':            city = dict_weather['data']['city'] if 'city' in dict_weather['data'].keys() else None # 获取城市名            wendu = dict_weather['data']['wendu'] + '℃ ' if 'wendu' in dict_weather['data'].keys() else None  # 获取今天当前温度            month = time.strftime('%m')  # 获取今天对应的月份            forecast = dict_weather['data']['forecast']            date = month + '月' + forecast[0]['date'] if 'date' in forecast[0].keys() else None  # 获取日期            type = forecast[0]['type'] if 'type' in forecast[0].keys() else None  # 获取天气类型            fengxiang = forecast[0]['fengxiang'] if 'fengxiang' in forecast[0].keys() else None  # 获取风向            fengli = forecast[0]['fengli'] if 'fengli' in forecast[0].keys() else None  # 获取风力            high = forecast[0]['high'] if 'high' in forecast[0].keys() else None  # 获取最高温度            low = forecast[0]['low'] if 'low' in forecast[0].keys() else None  # 获取最低温度    except Exception as err:        print('错误: ' + str(err))if __name__ == "__main__":    print('
查询珠海今天天气: 
')    get_weather_today(cityName='珠海')    print('城市: ' + city)    print('日期: ' + date)    print('天气: ' + type)    print('风向: ' + fengxiang)    print('风力: ' + fengli)    print('最高温度: ' + high)    print('最低温度: ' + low)

上述代码运行结果:

python查询珠海今天的天气结果图

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章