This article mainly introduces the python code for implementing real-time weather information by using APIs. It is very practical and can be used as a reference by anyone who needs it. Python uses APIs to implement real-time weather information
Import urllib. requestimport urllib. parseimport json "" capture real-time weather conditions using the "most beautiful weather" http://www.zuimeitianqi.com/ "Class ZuiMei (): def _ init _ (self): self. url =' http://www.zuimeitianqi.com/ Zuimei/queryWeather 'self. headers = {} self. headers ['user-agent'] = 'mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/47.0.2526.80 Safari/537.36 '# id information of some cities self. cities = {} self. cities ['chengdu '] = '000000' self. cities ['hangzhou'] = '000000' self. cities ['shenzhen '] = '000000' self. cities ['guangzhou '] = '000000' self. cities ['shanghai'] = '000000' self. cities ['beijing'] = '000000' # Form Data self. data = {} self. city = 'beijing' def query (self, city = 'beijing'): if city not in self. cities: print ('current city not supported temporarily ') return self. city = city data = urllib. parse. urlencode ({'citycode': self. cities [self. city]}). encode ('utf-8') req = urllib. request. request (self. url, data, self. headers) response = urllib. request. urlopen (req) html = response. read (). decode ('utf-8') # parse json data and print the result self. json_parse (html) def json _ Parse (self, html): target = json. loads (html) high_temp = target ['data'] [0] ['actual'] ['high'] low_temp = target ['data'] [0] ['actual'] ['low' '] current_temp = target ['data'] [0] ['actual'] ['tmp'] today_wea = target ['data'] [0] ['actual'] ['wea'] air_desc = target ['data'] [0] ['actual'] ['desc'] # Shanghai 6 ~ -2 °C current temperature 1 °C humidity: 53 air quality is not good, pay attention to haze prevention. Print ('% s: % s ~ % S °C current temperature % s °C humidity: % s % s' % (self. city, high_temp, low_temp, current_temp, today_wea, air_desc) if _ name _ = '_ main _': zuimei = ZuiMei () zuimei. query ('guangzhou ')
Demo: