This article mainly introduces how to obtain weather information from Baidu API by using Python. The example analyzes the skills of using Python to operate Baidu API, which has some reference value, for more information about how to obtain weather conditions from Baidu API, see the example in this article. Share it with you for your reference. The specific implementation method is as follows:
The code is as follows:
_ Author _ = 'Saint'
Import OS
Import urllib. request
Import urllib. parse
Import json
Class weather (object ):
# Retrieve the uri of the city code
Code_uri = "http://apistore.baidu.com/microservice/cityinfo? Cityname ="
# Retrieve the weather information uri
Weather_uri = "http://apistore.baidu.com/microservice/weather? Cityid ="
# Main processing logic
Def mainHandle (self ):
Print ("Enter the weather you want to query :")
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 ["time"] + "\ 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 Python programming.