python結(jié)合API實現(xiàn)即時天氣信息
更新時間:2016年01月19日 08:57:07 投稿:hebedich
這篇文章主要介紹了python結(jié)合API實現(xiàn)即時天氣信息的代碼,非常的實用,有需要的小伙伴可以參考下。
python結(jié)合API實現(xiàn)即時天氣信息
import urllib.request
import urllib.parse
import json
"""
利用“最美天氣”抓取即時天氣情況
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信息
self.cities = {}
self.cities['成都'] ='01012703'
self.cities['杭州'] = '01013401'
self.cities['深圳'] = '01010715'
self.cities['廣州'] = '01010704'
self.cities['上海'] = '01012601'
self.cities['北京'] = '01010101'
# Form Data
self.data = {}
self.city = '北京'
def query(self,city='北京'):
if city not in self.cities:
print('暫時不支持當前城市')
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')
# 解析json數(shù)據(jù)并打印結(jié)果
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']
# 上海 6~-2°C 現(xiàn)在溫度 1°C 濕度:53 空氣質(zhì)量不好,注意防霾。
print('%s: %s~%s°C 現(xiàn)在溫度 %s°C 濕度:%s %s'%(self.city,high_temp,low_temp,current_temp,today_wea,air_desc))
if __name__ == '__main__':
zuimei = ZuiMei()
zuimei.query('廣州')
效果演示:

相關(guān)文章
完美解決Python matplotlib繪圖時漢字顯示不正常的問題
今天小編就為大家分享一篇完美解決Python matplotlib繪圖時漢字顯示不正常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Python?作為小程序后端的三種實現(xiàn)方法(推薦)
這篇文章主要介紹了Python?作為小程序后端的三種方法,在這比較推薦前兩種方法,本文通過實例圖文相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下2022-05-05
Python英文詞頻統(tǒng)計(哈姆雷特)程序示例代碼
在文本處理方面,Python也有著得天獨厚的優(yōu)勢,不僅提供了多種字符串操作函數(shù),而且還可以使用各種開源庫來處理文本,下面這篇文章主要給大家介紹了關(guān)于Python英文詞頻統(tǒng)計(哈姆雷特)程序示例的相關(guān)資料,需要的朋友可以參考下2023-06-06

