圆月山庄资源网 Design By www.vgjia.com

本文实例讲述了Python实现从百度API获取天气的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:__author__ = 'saint'
import os
import urllib.request
import urllib.parse
import json
class weather(object):
    # 获取城市代码的uri
    code_uri = "http://apistore.baidu.com/microservice/cityinfo"
    # 获取天气信息的uri
    weather_uri = "http://apistore.baidu.com/microservice/weather"
    # 主处理逻辑
    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 + "\r\n"
                output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "\r\n"
                output += "天气:" + ret_data["weather"] + " [" + ret_data["WD"] + ret_data["WS"] + "]\r\n"
                output += "当前温度:" + ret_data["temp"] + " (" + ret_data["h_tmp"] + " ---> " + ret_data["l_tmp"] + ")\r\n"
                print(output)
                return True
            else:
                print(data['errMsg'])
                return False
if __name__ == "__main__":
    weather = weather()
    weather.mainHandle()

希望本文所述对大家的Python程序设计有所帮助。

标签:
Python,百度API,获取天气,方法

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com