基于python的-天气预报查询系统(json解析)

# 天气预报
# 引入 requests
import requests
# 引入python中内置的包json,用来解析和生成json数据的
import json

city = input('请输入要查询的城市:')
# url 统一资源定位符
# windows + r cmd 打开命令行工具 输入pip install requests

url = 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak' \
      '=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?.' % city

# 使用requests发起请求,接收返回的结果
rs = requests.get(url)
# 使用loads函数,将json字符串转换为python的字典或列表
rs_dict = json.loads(rs.text)
# 取出error
error_code =  rs_dict['error']
# 如果取出的error0,表示数据正常,否则没有查询到结果
if error_code == 0:
      # 从字典中取出数据
      results = rs_dict['results']
      # 根据索引取出城市天气信息字典
      info_dict = results[0]
      # 根据字典的key,取出城市名称
      city_name = info_dict['currentCity']
      # 取出pm      pm25 = info_dict['pm25']
      print('当前城市:%s pm值:%s' % (city_name,pm25))
      # 取出天气信息列表
      weather_data = info_dict['weather_data']
      # for循环取出每一天天气的小字典
      for weather_dict in weather_data:
           # 取出日期、天气、风级、温度
            date = weather_dict['date']
            weather = weather_dict['weather']
            wind = weather_dict['wind']
            temperature = weather_dict['temperature']
            print('%s %s %s %s' % (date, weather, wind,temperature ))

else:
      print('没有查询到天气信息!')
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值