日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

可靠免费的天气接口

發布時間:2024/3/24 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 可靠免费的天气接口 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

請訪問我的github項目module-weather獲取源程序,在這里只是長話短說


搜索了一下天氣接口,發現很多都是收費接口,或者免費調用但是有次數限制。 因為項目上剛好用到天氣模塊,但是又不需要很具體的天氣信息,所以萌生了開發一個基于中國天氣數據的接口,中國天氣的接口訪問速度很快而且很穩定。
訪問中國天氣的接口有件麻煩事就是需要城市代碼來查詢。網上一搜城市代碼,發現很多都是復制粘貼過來的。并沒有json,xml等方便調用的格式。所以這個小項目的主要工作就是獲取這些城市代碼數據,所以說工作量不是很大。

直接上代碼
1. 小爬蟲

# !/usr/bin/env python # -*- coding: utf-8 -*-import json import pickle import urllib.request as request from lxml import etreeurl = 'http://cj.weather.com.cn/support/detail.aspx?id=51837fba1b35fe0f8411b6df' save_dir = 'citycode.pkl'try:r = request.Request(url)response = request.urlopen(r)html = response.read()#print(html)selector = etree.HTML(html)data = selector.xpath('//div[@class="entry-content"]//p/text()')[0:]code_dict = {}# 注意到北京分隔符有中文逗號也有西文逗號故獨立出來處理code_dict['北京'] = data[0].strip().split(',')[0]for item in data[1:]:arr = item.strip().split(',')code_dict[arr[1]] = arr[0]print(code_dict)with open(save_dir, 'wb') as f:pickle.dump(code_dict, f, True)with open('./dict.json', 'w') as f:json.dump(code_dict, f, ensure_ascii=False) except Exception as e: print('faild> ', e)

訪問接口

# !/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'}] }

附上城市代碼下載地址

  • csdn資源庫 ,本想免積分的,可最低分要1分,所以土豪隨意咯
  • github文件 免積分,推薦
  • 總結

    以上是生活随笔為你收集整理的可靠免费的天气接口的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。