Python小工具——通过API获取天气预报

Python通过API获取天气预报

    闲来无事,用Python实现了一个小工具,通过实现API来获取当前的天气预报。

获取API的key

    在阿凡达数据上查找天气预报相关的API,注册申请可获得一个key。API有详尽的文档,会返回Json格式的一堆数据,我们解析出来即可。非常简单。话不多说,上代码吧。

实现


#注意:先安装requests。
# -*- coding: utf-8 -*-  

import requests

class WeatherReport():
    def __init__(self,cityName):
        self.Url = 'http://api.avatardata.cn/Weather/Query'
        self.AppKey = '23f69de012da4306815193a00eca0230'
        self.Value = {'key':self.AppKey, 'cityname':cityName}

    def GetContent(self):
        content = requests.get(self.Url,params=self.Value)
        jsContent = content.json()
        return jsContent

    def FormartContent(self):
        jsContent = self.GetContent()
        date = jsContent['result']['realtime']

        jsWeather = jsContent['result']['weather'][0]
        allContent = {}
        allContent['AddressAndTime'] = date['city_name'] + " ** " + jsWeather['date'] + " ** " + jsWeather['nongli'] + u" ** 星期" + jsWeather['week']
        allContent['WeatherInfo'] = self.GetWeatherInfo(jsWeather['info'])

        jsLife = jsContent['result']['life']
        allContent['LifeInfo'] = self.GetLifeInfo(jsLife['info'])

        strContent = ""
        strContent = strContent + allContent['AddressAndTime']+"\n"
        strContent = strContent + "******************************************" + "\n"
        strContent = strContent + allContent['WeatherInfo']
        strContent = strContent + "******************************************" + "\n"
        strContent = strContent + allContent['LifeInfo']
        print strContent

    def GetLifeInfo(self,info):
        iIndex = 0
        LifeInfo = {}
        for item in info.values():
            if (type(item) is not list):
                iIndex = iIndex+1
                continue
            if (0 == iIndex):
                LifeInfo['chuanyi'] = u"穿  衣: " + item[1]
            if (1 == iIndex):
                LifeInfo['kongtiao'] = u"空  调: " + item[1]
            if (2 == iIndex):
                LifeInfo['yundong'] = u"运  动: " + item[1]
            if (3 == iIndex):
                LifeInfo['xiche'] = u"紫外线: " + item[1]
            if (4 == iIndex):
                LifeInfo['wuran'] = u"洗  车: " + item[1]
            if (5 == iIndex):
                LifeInfo['ziwaixian'] = u"感  冒: " + item[1]
            if (6 == iIndex):
                LifeInfo['ganmao'] = u"污  染: " + item[1]
            iIndex = iIndex +1

        strContent = ""
        for item in LifeInfo.values():
            strContent = strContent + item + "\n"

        return strContent

    def GetWeatherInfo(self,info):
        iIndex = 0
        weatherInfo = {}
        for item in info.values():
            if (type(item) is not list):
                iIndex = iIndex + 1
                continue
            strContent = self.FormartWeatherInfo(item)
            if (0 == iIndex):
                weatherInfo['dawn'] = strContent
            if (1 == iIndex):
                weatherInfo['day'] = strContent
            if (2 == iIndex):
                weatherInfo['night'] = strContent
            iIndex = iIndex + 1

        strContent = ""
        for item in weatherInfo.values():
            strContent = strContent + item + "\n"

        return strContent

    def FormartWeatherInfo(self,contents):
        iIndex = 0
        strContent = ""
        listContent = []
        for item in contents:
            if (0 == iIndex):
                iIndex = iIndex + 1
                continue
            if (1 == iIndex):
                strContent = u"当前天气:"
            if (2 == iIndex):
                strContent = u"当前温度: "
            if (3 == iIndex):
                strContent = u"当前风向: "
            if (4 == iIndex):
                strContent = u"风力等级: "
            if (5 == iIndex):
                strContent = u"刷新时间: "
            if (6 == iIndex):
                strContent = u"温馨提示: "
            strContent = strContent + contents[iIndex]
            iIndex = iIndex + 1
            listContent.append(strContent)
        strContent = ""
        for iter in listContent:
            strContent = strContent + iter + "\n"
        return strContent

weatherObj = WeatherReport("西安")        
weatherObj.FormartContent()

输出

西安 * 2017-08-18 * 闰六月廿七 ** 星期五


当前天气:多云
当前温度: 33
当前风向: 东北风
风力等级: 微风
刷新时间: 06:09

当前天气:多云
当前温度: 24
当前风向: 东北风
风力等级: 微风
刷新时间: 19:29


穿 衣: 天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。
空 调: 天气热,到中午的时候您将会感到有点热,因此建议在午后较热时开启制冷空调。
运 动: 天气较好,较适宜进行各种运动,但因天气热,请适当减少运动时间,降低运动强度。
感 冒: 各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
紫外线: 属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。
洗 车: 较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 可以参考下面的代码示例,使用 Python获取天气预报:import requests# Get the response from OpenWeatherMap response = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk')# Convert the response to a Python dictionary weather_data = response.json()# Get the temperature from the dictionary temperature = weather_data['main']['temp'] ### 回答2: 获取天气预报可以使用Python的第三方库requests和json。 以下是一个简单的代码示例: ```python import requests import json def get_weather(city_name): # 设置API接口的URL和参数 url = "https://api.seniverse.com/v3/weather/daily.json" params = { "key": "your_api_key", # 替换成你的API Key "location": city_name, # 替换成要查询的城市 "language": "zh-Hans", "unit": "c" # 单位设为摄氏度 } try: # 发送GET请求获取天气数据 response = requests.get(url, params=params) data = response.json() # 解析JSON数据并提取所需天气信息 results = data["results"][0] location = results["location"]["name"] now_weather = results["daily"][0] date = now_weather["date"] text_day = now_weather["text_day"] high_temperature = now_weather["high"] low_temperature = now_weather["low"] # 打印天气信息 print(f"{location} {date}:{text_day},最高温度:{high_temperature}℃,最低温度:{low_temperature}℃") except: print("获取天气信息失败") # 输入要查询的城市并调用函数获取天气信息 city = input("请输入要查询的城市:") get_weather(city) ``` 请注意,上述示例代码使用了心知天气的API接口,需要在`params`字典中填入自己的API Key才能正常使用。同时,本代码示例只获取了当天的天气信息,若需要获取更多天数的天气预报,可以修改`params`中的`start`和`days`参数。 ### 回答3: 以下是一个使用Python获取天气预报的简单代码示例: ```python import requests def get_weather_forecast(city): # 构造请求URL url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY" try: # 发送HTTP GET请求 response = requests.get(url) if response.status_code == 200: # 解析JSON响应数据 weather_data = response.json() # 提取天气信息 weather = weather_data['weather'][0]['description'] temperature = weather_data['main']['temp'] humidity = weather_data['main']['humidity'] # 打印天气预报 print(f"城市:{city}") print(f"天气:{weather}") print(f"温度:{temperature}") print(f"湿度:{humidity}") else: print("获取天气预报失败") except requests.exceptions.RequestException: print("发生网络请求错误") # 调用函数获取天气预报 get_weather_forecast("上海") ``` 以上代码使用了requests库发送HTTP GET请求,通过OpenWeatherMap API获取天气预报的JSON数据,并进行解析,打印出城市、天气、温度和湿度信息。需要替换`YOUR_API_KEY`为自己的API密钥来访问OpenWeatherMap API
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值