共计 2311 个字符,预计需要花费 6 分钟才能阅读完成。
本文转自 SDK 社区:sdk.cn
一、开明接口
天气预报接口服务应用的聚合数据提供的收费接口,每天能够 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()
四、返回后果
正文完