python結合API實現即時天氣信息
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數據并打印結果
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 現在溫度 1°C 濕度:53 空氣質量不好,注意防霾。
print('%s: %s~%s°C 現在溫度 %s°C 濕度:%s %s'%(self.city,high_temp,low_temp,current_temp,today_wea,air_desc))
if __name__ == '__main__':
zuimei = ZuiMei()
zuimei.query('廣州')
效果演示:
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

