Python实现从百度API获取天气的方法

yipeiwu_com5年前Python基础

本文实例讲述了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?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 + "\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实现输入数字的连续加减方法

不用库,写了很久,一直出bug,到网上一搜,可以直接输入之后,eval(str)即可得到结果! eval程序如下: s=input("请输入要运算的数字") print("The r...

python3 打开外部程序及关闭的示例

如下所示: import os import time import subprocess subprocess.Popen(r'cmd') print('打开成功') time...

用Python画一个LinkinPark的logo代码实例

用Python画一个LinkinPark的logo代码实例

这篇文章主要介绍了用Python画一个LinkinPark的logo代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下...

Python 性能优化技巧总结

1.使用测量工具,量化性能才能改进性能,常用的timeit和memory_profiler,此外还有profile、cProfile、hotshot等,memory_profiler用了...

详解python列表(list)的使用技巧及高级操作

1、合并列表(extend) 跟元组一样,用加号(+)将两个列表加起来即可实现合并: In [1]: x=list(range(1, 13, 2)) In [2]: x + ['b'...