基于Python的免费天气预报接口查询
短信预约 -IT技能 免费直播动态提醒
一、开通接口
天气预报接口服务使用的聚合数据提供的免费接口,每天可以100次免费调用。可以通过https://www.juhe.cn/docs/api/id/73注册及开通。
二、Python2.x调用示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib, urllib2, sys, json
reload(sys)
sys.setdefaultencoding('utf-8')
url = 'http://apis.juhe.cn/simpleWeather/query'
params = {
"city": "北京", # 查询天气的城市名称,如:北京、苏州、上海
"key": "xxxxxxxx", # 您申请的接口API接口请求Key
}
querys = urllib.urlencode(params)
request = urllib2.Request(url, data=querys)
response = urllib2.urlopen(request)
content = response.read()
if (content):
try:
result = json.loads(content)
error_code = result['error_code']
if (error_code == 0):
temperature = result['result']['realtime']['temperature']
humidity = result['result']['realtime']['humidity']
info = result['result']['realtime']['info']
wid = result['result']['realtime']['wid']
direct = result['result']['realtime']['direct']
power = result['result']['realtime']['power']
aqi = result['result']['realtime']['aqi']
print("温度:%s\n湿度:%s\n天气:%s\n天气标识:%s\n风向:%s\n风力:%s\n空气质量:%s" % (temperature, humidity, info, wid, direct, power, aqi))
else:
print("请求失败:%s %s" % (result['error_code'], result['reason']))
except Exception as e:
print("解析结果异常:%s" % e)
else:
# 可能网络异常等问题,无法获取返回内容,请求异常
print("请求异常")
三、Python3.x调用示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib.request as request
import urllib.error as error
import json
# 天气预报查询示例
def main():
api_url = 'http://apis.juhe.cn/simpleWeather/query'
params_dict = {
"city": "北京", # 查询天气的城市名称,如:北京、苏州、上海
"key": "xxxxxxxx", # 您申请的接口API接口请求Key
}
params = urllib.parse.urlencode(params_dict)
try:
req = request.Request(api_url, params.encode())
response = request.urlopen(req)
content = response.read()
if content:
try:
result = json.loads(content)
error_code = result['error_code']
if (error_code == 0):
temperature = result['result']['realtime']['temperature']
humidity = result['result']['realtime']['humidity']
info = result['result']['realtime']['info']
wid = result['result']['realtime']['wid']
direct = result['result']['realtime']['direct']
power = result['result']['realtime']['power']
aqi = result['result']['realtime']['aqi']
print("温度:%s\n湿度:%s\n天气:%s\n天气标识:%s\n风向:%s\n风力:%s\n空气质量:%s" % (
temperature, humidity, info, wid, direct, power, aqi))
else:
print("请求失败:%s %s" % (result['error_code'], result['reason']))
except Exception as e:
print("解析结果异常:%s" % e)
else:
# 可能网络异常等问题,无法获取返回内容,请求异常
print("请求异常")
except error.HTTPError as err:
print(err)
except error.URLError as err:
# 其他异常
print(err)
if __name__ == '__main__':
main()
四、返回结果
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341