成都市规划局,白莲艳史,废弃皇妃
本文实例讲述了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查看网页代码的方法:1、使用“import”导入requests包import requests2、使用requests包的get()函数通过网页...
[阅读全文]
-
-
python如何保存文本文件
python保存文本文件的方法:使用python内置的open()类可以打开文本文件,向文件里面写入数据可以用write()函数,写完之后,使用close()函...
[阅读全文]
-
python如何编写win程序
python可以编写win程序。win程序的格式是exe,下面我们就来看一下使用python编写exe程序的方法。编写好python程序后py2exe模块即可将...
[阅读全文]
-
-
-
-
-
-
网友评论