加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

从百度的API获取天气

发布时间:2020-05-24 23:40:28 所属栏目:Python 来源:互联网
导读:从百度的API获取天气

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

__author__ = 'saint'

import os
import urllib.request
import urllib.parse
import json

class weather(object):

    # 获取城市代码的uri
    code_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="

    # 获取天气信息的uri
    weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="

    # 主处理逻辑
    def mainHandle(self):
        print("输入你要查询的天气:")
        city_name = input()
        uri = self.code_uri + urllib.parse.quote(city_name)
        ret = json.loads(urllib.request.urlopen(uri).read().decode("utf8"))
        if ret['errNum'] != 0:
            print(ret['retMsg'])
            return False
        else:
            weather_uri = self.weather_uri + ret['retData']['cityCode']
            data = json.loads(urllib.request.urlopen(weather_uri).read().decode("utf8"))
            if data['errNum'] == 0:
                ret_data = data['retData']
                output = "城市名:" + city_name + "rn"
                output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "rn"
                output += "天气:" + ret_data["weather"] + " [" + ret_data["WD"] + ret_data["WS"] + "]rn"
                output += "当前温度:" + ret_data["temp"] + " (" + ret_data["h_tmp"] + " ---> " + ret_data["l_tmp"] + ")rn"
                print(output)
                return True
            else:
                print(data['errMsg'])
                return False

if __name__ == "__main__":
    weather = weather()
    weather.mainHandle()

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读