Python實現(xiàn)從百度API獲取天氣的方法
更新時間:2015年03月11日 09:26:39 作者:saintatgod
這篇文章主要介紹了Python實現(xiàn)從百度API獲取天氣的方法,實例分析了Python操作百度API的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python實現(xiàn)從百度API獲取天氣的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
復制代碼 代碼如下:
__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()
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中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題
今天小編就為大家分享一篇解決python中畫圖時x,y軸名稱出現(xiàn)中文亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

