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

yipeiwu_com6年前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批量处理文件或文件夹

本文实例为大家分享了python批量处理文件或文件夹的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import os,shutil impor...

Python连接数据库学习之DB-API详解

Python连接数据库学习之DB-API详解

前言 大家都知道在Python中如果要连接数据库,不管是MySQL、SQL Server、PostgreSQL亦或是SQLite,使用时都是采用游标的方式,所以就不得不学习Python...

python 队列基本定义与使用方法【初始化、赋值、判断等】

python 队列基本定义与使用方法【初始化、赋值、判断等】

本文实例讲述了python 队列基本定义与使用方法。分享给大家供大家参考,具体如下: 队列的特征是:先进先出 应用场景:消息通信、多进程间的协同、多线程间的协同等 在队列中需要设计的实例...

python安装scipy的方法步骤

python安装scipy的方法步骤

Scipy高级科学计算库:和Numpy联系很密切,Scipy一般都是操控Numpy数组来进行科学计算、统计分析,所以可以说是基于Numpy之上了。 Scipy库的安装 pip ins...

Python Unittest根据不同测试环境跳过用例的方法

Python Unittest根据不同测试环境跳过用例的方法

前言 在利用单元测试框架执行测试用例的过程中,有时只需要执行一部分用例,或者跳过某些暂不需要执行的用例,python的unittest框架就内置这样的功能。 本文章会讲述以下几个内容:...