码迷,mamicode.com
首页 > 其他好文 > 详细

天气预报

时间:2020-04-30 11:36:08      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:http   erro   urlopen   json   ==   import   error   天气预报   url   

import json, urllib
import urllib.request
from urllib.parse import urlencode

def main():
# 配置您申请的APPKey
appkey = "3acd93b81aa4cec158184f53b8629e9e"
# 1.根据城市查询天气
request1(appkey, "GET")
# 根据城市查询天气
def request1(appkey, m="GET"):
url = "http://op.juhe.cn/onebox/weather/query"
cityname = "北京"
params = {
"cityname": cityname, # 要查询的城市,如:温州、上海、北京
"key": appkey, # 应用APPKEY(应用详细页查询)
"dtype": "", # 返回数据的格式,xml或json,默认json

}
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)
# print(res)
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()

天气预报

标签:http   erro   urlopen   json   ==   import   error   天气预报   url   

原文地址:https://www.cnblogs.com/lurj/p/12807506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!