发布于 2015-03-21 07:58:41 | 269 次阅读 | 评论: 0 | 来源: 网友投递
Python编程语言
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
本文实例讲述了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 + "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()