How to obtain weather from Baidu API using Python

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.