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 pyinotify模块实现对文档的实时监控功能方法

0x01 安装pyinotify >>> pip install pyinotify >>> import pyinotify 0x02 实现对...

python 基础教程之Map使用方法

Python Map Map会将一个函数映射到一个输入列表的所有元素上。Map的规范为:map(function_to_apply, list_of_inputs) 大多数时候,我们需...

python常用知识梳理(必看篇)

接触python已有一段时间了,下面针对python基础知识的使用做一完整梳理: 1)避免‘\n'等特殊字符的两种方式: a)利用转义字符‘\' b)利用原始字符‘r' prin...

Python与R语言的简要对比

Python与R语言的简要对比

数据挖掘技术日趋成熟和复杂,随着互联网发展以及大批海量数据的到来,之前传统的依靠spss、SAS等可视化工具实现数据挖掘建模已经越来越不能满足日常需求,依据美国对数据科学家(data s...

python xml.etree.ElementTree遍历xml所有节点实例详解

python xml.etree.ElementTree遍历xml所有节点 XML文件内容: <students> <student name='刘备' s...