Python3 urllib获取天气预报

使用阿里云免费提供的天气预报接口

"https://market.aliyun.com/products/57126001/cmapi014302.html?spm=5176.2020520132.101.6.7d967218nGsr1g"获取天气预报信息

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,询问过客服后才知道,接口对每分钟访问总流控有限制,所以现在每分钟基本上只能访问成功一两次.所以想要完美的使用只能花钱使用收费版了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值