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()

 

你可能感兴趣的:(python,接口自动化)