可靠免费的天气接口
請訪問我的github項目module-weather獲取源程序,在這里只是長話短說
搜索了一下天氣接口,發現很多都是收費接口,或者免費調用但是有次數限制。 因為項目上剛好用到天氣模塊,但是又不需要很具體的天氣信息,所以萌生了開發一個基于中國天氣數據的接口,中國天氣的接口訪問速度很快而且很穩定。
訪問中國天氣的接口有件麻煩事就是需要城市代碼來查詢。網上一搜城市代碼,發現很多都是復制粘貼過來的。并沒有json,xml等方便調用的格式。所以這個小項目的主要工作就是獲取這些城市代碼數據,所以說工作量不是很大。
直接上代碼
1. 小爬蟲
訪問接口
# !/usr/bin/env python # -*- coding: utf-8 -*-import datetime import requests from utils import * from requests.packages.urllib3.exceptions import InsecureRequestWarning #禁用安全警告 requests.packages.urllib3.disable_warnings(InsecureRequestWarning)class Weather(object):def __init__(self, city, type='forecast'):self.type = typeself.single_url = Noneself.multi_url = Nonecode = get_code(city)if code != None:self.single_url = 'http://www.weather.com.cn/data/sk/{}.html'.format(code)self.multi_url = 'http://mobile.weather.com.cn/data/forecast/{}.html'.format(code)def process(self):if self.type == 'forecast':result = self.get_multi()else:result = self.get_single()return resultdef get_multi(self):result = {}if self.multi_url != None:r = requests.get(self.multi_url, verify=False)try:json = eval(str(r.content, 'utf-8'))result['type'] = 'forecast'result['city'] = json['c']['c3']result['results'] = []for i, item in enumerate(list(json['f']['f1'])):now = datetime.datetime.now()delta = datetime.timedelta(days=i)n_days = now + deltadate = n_days.strftime('%Y-%m-%d')temp = [item['fc'], item['fd']]info = {'date': date,'temperature': {'low': min(temp),'high': max(temp)},'sunrise': item['fi'].split('|')[0],'sunset': item['fi'].split('|')[1]}result['results'].append(info)except Exception as e:print('error ', e)return resultdef get_single(self):result = {}if self.single_url != None:r = requests.get(self.single_url, verify=False)try:json = eval(str(r.content, 'utf-8'))result['type'] = 'realtime'result['city'] = json['weatherinfo']['city']result['temperature'] = json['weatherinfo']['temp'] result['wind'] = json['weatherinfo']['WD']result['rain'] = json['weatherinfo']['rain']except:return resultreturn resultif __name__=='__main__':city = '深圳'print(city, '實時天氣')print(Weather(city, 'realtime').process())print(city, '未來七天天氣') print(Weather(city).process())實現效果
深圳實時天氣 {'type': 'realtime', 'city': '深圳', 'temperature': '21', 'wind': '南風', 'rain': '0'}深圳未來七天天氣 {'type': 'forecast', 'city': '深圳', 'results': [{'date': '2017-08-31', 'temperature': {'low': '25', 'high': '32'}, 'sunrise': '06:18', 'sunset': '18:01'}, {'date': '2017-09-01', 'temperature': {'low': '25', 'high': '31'}, 'sunrise': '06:19', 'sunset': '18:00'}, {'date': '2017-09-02', 'temperature': {'low': '24', 'high': '27'}, 'sunrise': '06:19', 'sunset': '17:59'}, {'date': '2017-09-03', 'temperature': {'low': '21', 'high': '25'}, 'sunrise': '06:20', 'sunset': '17:58'}, {'date': '2017-09-04', 'temperature': {'low': '19', 'high': '23'}, 'sunrise': '06:20', 'sunset': '17:57'}, {'date': '2017-09-05', 'temperature': {'low': '20', 'high': '23'}, 'sunrise': '06:20', 'sunset': '17:56'}, {'date': '2017-09-06', 'temperature': {'low': '22', 'high': '25'}, 'sunrise': '06:21', 'sunset': '17:56'}] }附上城市代碼下載地址
總結
- 上一篇: 小i机器人微信版
- 下一篇: CPython入门----Fork源码到