This example describes Python's approach to getting the weather from the Baidu API. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
__author__ = ' Saint '
Import OS
Import Urllib.request
Import Urllib.parse
Import JSON
Class Weather (object):
# get the URI of the city code
Code_uri = "Http://apistore.baidu.com/microservice/cityinfo?cityname="
# get the URI of the weather information
Weather_uri = "Http://apistore.baidu.com/microservice/weather?cityid="
# Main processing logic
def mainhandle (self):
Print ("Enter the weather you want to inquire about:")
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:" + city_name + "\ r \ n"
Output + + "Update Time:" + ret_data["date"] + "" + ret_data["times" + "\ r \ n"
Output + = "weather:" + ret_data["weather"] + "[" + ret_data["WD"] + ret_data["WS" + "]\r\n"
Output = "Current temperature:" + 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 ()
I hope this article will help you with your Python programming.