使用阿里云免费提供的天气预报接口
import ssl
from urllib import request
from urllib import parse
import json
def __GetWeatherData(city):
host = 'https://jisutqybmf.market.alicloudapi.com'
path = '/weather/query'
appcode = '自己的appcode'
querys = ('city=%s&citycode=citycode&cityid=cityid&ip=ip&location=location' % parse.quote(city))
url = host + path + '?' + querys
try:
rs = request.Request(url)
rs.add_header('Authorization', 'APPCODE ' + appcode)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = request.urlopen(rs, context=ctx, timeout=5)
content = response.read()
return content.decode('utf-8')
except Exception as ex:
a = ex
return 'aliError'
获取到的天气数据是json数据,根据个人需要进行解析提取
def GetWeather(city):
resultStr = __GetWeatherData(city) #获取城市天气数据
if resultStr != 'aliError':
str=''
json_dict = json.loads(resultStr)
if 'result' in json_dict:
info = json.dumps(json_dict['result'])
data = json.loads(info)
str+='城市:%s 日期:%s %s\n天气:%s\n当前气温:%s℃\n最高气温:%s℃\n最低气温:%s℃\n风向:%s 风级:%s\n ' % (
data['city'], data['date'], data['week'], data['weather'], data['temp'], data['temphigh'], data['templow'],
data['winddirect'], data['windpower'])
if 'index' in data:
indexI= json.dumps(data['index'])
indexD= json.loads(indexI)
for item in indexD:
str+='\n'+item['iname']
str+='\n'+item['detail']+'\n'
return str
else:
return resultStr
该接口刚开放时查询速度很不错,后来再使用时提示403,询问过客服后才知道,接口对每分钟访问总流控有限制,所以现在每分钟基本上只能访问成功一两次.所以想要完美的使用只能花钱使用收费版了