官方提供的是pyhon2的代碼,我改造了一下
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import urllib.request
from urllib.parse import urlencode
# ----------------------------------
# 天氣預報調用示例代碼 - 聚合數據
# 在線接口文檔:http://www.juhe.cn/docs/73
# ----------------------------------
def main():
# 配置您申請的APPKey
appkey = "XXXXXX"
# 1.根據城市查詢天氣
request1(appkey, "GET")
# 根據城市查詢天氣
def request1(appkey, m="GET"):
url = "http://v.juhe.cn/weather/index"
params = {
"cityname": "上海", # 要查詢的城市,如:溫州、上海、北京
"key": appkey, # 應用APPKEY(應用詳細頁查詢)
"dtype": "json", # 返回數據的格式,xml或json,默認json
"format": 1
}
params = urlencode(params)
if m == "GET":
f = urllib.request.urlopen("%s?%s" % (url, params))
else:
f = urllib.request.urlopen(url, params)
content = f.read()
res = json.loads(content)
if res:
error_code = res["error_code"]
if error_code == 0:
# 成功請求
print(res["result"])
else:
print("%s:%s" % (res["error_code"], res["reason"]))
else:
print("request api error")
if __name__ == '__main__':
main()
使用requests
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
# ----------------------------------
# 天氣預報調用示例代碼 - 聚合數據
# 在線接口文檔:http://www.juhe.cn/docs/73
# ----------------------------------
def main():
# 配置您申請的APPKey
appkey = "##¥%……………………"
# 1.根據城市查詢天氣
request1(appkey)
# 根據城市查詢天氣
def request1(appkey):
url = "http://v.juhe.cn/weather/index"
params = {
"cityname": "上海", # 要查詢的城市,如:溫州、上海、北京
"key": appkey, # 應用APPKEY(應用詳細頁查詢)
"dtype": "json", # 返回數據的格式,xml或json,默認json
"format": 1
}
f = requests.get(url=url, params=params)
res = f.json()
if res:
error_code = res["error_code"]
print(error_code)
if error_code == 0:
# 成功請求
print(res["result"])
else:
print("%s:%s" % (res["error_code"], res["reason"]))
else:
print("request api error")
if __name__ == '__main__':
main()