【Python】利用网站API接口获取天气信息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kimidake/article/details/85054210

本文主要讲如何利用Python来获取天气信息。主要程序实现思路是从命令行传递坐标信息,然后利用天气预报网站的免费接口获取到相关天气信息,返回结果以json格式显示,并打印出需要的近3天天气情况。

信息源:https://openweathermap.org/

接口信息:http://api.openweathermap.org

#! python3
# quickWeather.py - 从命令行输入位置参数,从OpenWeatherMap获取近三天天气数据

import sys,requests,json

# 获取命令行参数
print(sys.argv[0])
if len(sys.argv) < 2:
    print('缺少位置信息')
    sys.exit()

location = ''.join(sys.argv[1:])

# 从网站获取数据(key几个小时后失效)
appid = '自己到网站注册账号后就会得到key'
response = requests.get(r'http://api.openweathermap.org/data/2.5/find?q=%s&cnt=3&lang=zh_cn&APPID=%s' % (location,appid))
response.raise_for_status()

# 加载并打印json数据
weatherData = json.loads(response.text)
info = weatherData['list']
address = info[0]['name']
today = info[0]['weather'][0]['description']
tomorrow = info[1]['weather'][0]['description']

print('''
    %s的天气状况:
        今天:%s
        明天:%s
'''%(address,today,tomorrow))

执行效果

执行结果

猜你喜欢

转载自blog.csdn.net/Kimidake/article/details/85054210