Python天气预报查询

功能: 实现城市天气预报查询,并提供未来四天查询

两个网站接口,直接返回数据,之后对数据进行读取和处理,很简单的小程序

效果图:
在这里插入图片描述
代码实现:

import urllib.request
import gzip
import json
print('------天气查询------')
def get_weather_data() :
    city_name = input('请输入要查询的城市名称:')
    url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
    url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
    #网址1只需要输入城市名,网址2需要输入城市代码
    #print(url1)
    weather_data = urllib.request.urlopen(url1).read()
    #读取网页数据
    weather_data = gzip.decompress(weather_data).decode('utf-8')
    #解压网页数据
    weather_dict = json.loads(weather_data)
    #将json数据转换为dict数据
    return weather_dict

def show_weather(weather_data):
    weather_dict = weather_data 
    #将json数据转换为dict数据
    if weather_dict.get('desc') == 'invilad-citykey':
        print('你输入的城市名有误,或者天气中心未收录你所在城市')
    elif weather_dict.get('desc') =='OK':
        forecast = weather_dict.get('data').get('forecast')
        print('城市:',weather_dict.get('data').get('city'))
        print('温度:',weather_dict.get('data').get('wendu')+'℃ ')
        print('感冒:',weather_dict.get('data').get('ganmao'))
        print('风向:',forecast[0].get('fengxiang'))
        print('风级:',forecast[0].get('fengli'))
        print('高温:',forecast[0].get('high'))
        print('低温:',forecast[0].get('low'))
        print('天气:',forecast[0].get('type'))
        print('日期:',forecast[0].get('date'))
        print('*******************************')
        four_day_forecast =input('是否要显示未来四天天气,是/否:')
        if four_day_forecast == '是' or 'Y' or 'y':
            for i in range(1,5):
                print('日期:',forecast[i].get('date'))
                print('风向:',forecast[i].get('fengxiang'))
                print('风级:',forecast[i].get('fengli'))
                print('高温:',forecast[i].get('high'))
                print('低温:',forecast[i].get('low'))
                print('天气:',forecast[i].get('type'))
                print('--------------------------')
    print('***********************************')

show_weather(get_weather_data())

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z小旋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值