基于Python3.x的接口调用

 1 # -*-coding: utf-8 -*-
 2 import urllib
 3 import urllib.request as request
 4 import urllib.error as error
 5 import json
 6 
 7 #天气预报查询
 8 def main():
 9     api_url = 'http://apis.juhe.cn/simpleWeather/query'
10     params_dict = {
11         "city": "广州",
12         "key": "123456789"
13     }
14     # 将dict类型参数转化为query_string格式(key=value&key=value),并且将中文转码,最终会转换为bytes(字节流)类型
15     # city=%E5%B9%BF%E5%B7%9E&key=123456789
16     params = urllib.parse.urlencode(params_dict)
17     try:
18         # urllib.request.Request()要求传递的data为bytes(字节流)类型
19         # 返回一个url请求对象
20         # <urllib.request.Request object at 0x0000000002DFF588>
21         req = request.Request(api_url, params.encode())
22         # urlopen 返回一个类文件对象
23         # <http.client.HTTPResponse object at 0x0000000002E09488>
24         response = request.urlopen(req)
25         content = response.read()
26         if content:
27             try:
28                 # json.loads()将json字符串转换为字典类型
29                 result = json.loads(content)
30                 print(result)
31                 error_code = result['error_code']
32                 if (error_code == 0):
33                     temperature = result['result']['realtime']['temperature']
34                     print("温度:%s" % temperature)
35             except Exception as e:
36                 print("解析结果异常:%s" % e)
37 
38     except error.HTTPError as err:
39         print(err)
40     except error.URLError as err:
41         print(err)
42 
43 if __name__ == '__main__':
44     main()

 

posted @ 2021-03-14 17:43  #天羽Owl  阅读(95)  评论(0编辑  收藏  举报