Python's way to get the weather from the Baidu API _python

Source: Internet
Author: User

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.

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.