python天气预报制作过程_python一个天气预报接口的demo

官方提供的是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()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值