爬虫系列实战:使用json解析天气数据

大家好,爬虫是一项非常抢手的技能,收集、分析和清洗数据是数据科学项目中最重要的部分,本文介绍使用json解析气象局天气数据。

在官网上获取天气数据信息,可以定义当前查询的位置,提取时间、温度、湿度、气压、风速等信息,并导入requests、matplotlib这些需要用到的库。

# 导入以下模块
import requests
import matplotlib.pyplot as plt
import pylab as pl

1.获取今日天气

调用api接口地址,获取天气数据接口,本文获取57494代表武汉的数据接口,进而获取json数据,并判断json请求是否成功。

def get_weather():
    # 调用api接口地址
    # 获取57494代表武汉的天气数据接口
    url = "https://weather.cma.cn/api/now/57494"

# 获取json数据
    json_datas = requests.get(url=url).json()
    #判断json请求是否成功?
    if json_datas.get("msg") == "success":
        # 请求成功
        json_location = json_datas.get("data").get("location")
        # 位置信息
        print('\n', '当前查询的位置'.center(50, '—'))
        print("城市代码: " + json_location.get("id") + "   城市名称: " + json_location.get("name") +"   详细地址: " + json_location.get("path"));
        # 当天天气信息
        json_now_data = json_datas.get("data").get("now")

        # 获取最新发布时间
        now_time = "最新天气发布时间:" + str(json_datas.get("data").get("lastUpdate"))
        print('\n',now_time.center(50, '—'))
        print("\n温度: " + str(json_now_data.get("temperature")) + "   气压: " + str(json_now_data.get("pressure")) +"  湿度: " + str(json_now_data.get("humidity")))
        print("\n风向: " + json_now_data.get("windDirection") + "   风力等级: " + json_now_data.get("windScale"))

    else:
        # 提示失败
        print("服务器返回的数据,失败了!")

2.可视化显示温度曲线

解析json数据,获取历史最大和最小的温度数据,进行图表绘制,可视化展示温度数据,使用绘图库输出可视化结果。

def get_Max_temperature():
    url = "https://weather.cma.cn/api/climate"
    # 1传数据参数
    params = {
                "stationid": 57494
            }
    # 2.获取json数据
    json_datas= requests.get(url=url, params=params).json()
    #print(json_datas)
    # 3.解析json数据,图表绘制
    data=json_datas.get("data").get("data")
    x = range(1, 13, 1) #显示12个月
    # 4.获取最大和最小的温度数据
    y = [maxTemp.get("maxTemp") for maxTemp in data]
    
    y1 = [minTemp.get("minTemp") for minTemp in data]

    pl.rcParams["font.sans-serif"] = ["SimHei"]
    plt.figure(figsize=(70, 70), dpi=100)
    plt.plot(x, y)
    plt.plot(x, y1)
    plt.xticks(x, ["{}月".format(i) for i in x])
    plt.title("1981年-2010年月平均气温和降水")
    plt.show()


if __name__ == "__main__":
    get_weather()

    get_Max_temperature()
    print('数据获取完成!!!')

天气查询APP,两种JSON解析方式 /** * 原始json数据解析 * */ // JSONObject jsonObject = new JSONObject(res); // String reason=jsonObject.getString("reason"); // if (reason.equals("参数不正确")){ // handler.sendEmptyMessage(1); // return; // } // JSONObject result=jsonObject.getJSONObject("result"); // JSONObject realtime=result.getJSONObject("realtime"); // JSONObject life=result.getJSONObject("life"); // JSONObject wind=realtime.getJSONObject("wind"); // String time=realtime.getString("time"); // JSONObject weather=realtime.getJSONObject("weather"); // String date=realtime.getString("date"); // dateStr=time+date; // weekStr=realtime.getString("week"); // calendarStr=realtime.getString("moon"); // windpowerStr=wind.getString("direct")+" "+wind.getString("power"); // weatherStr=weather.getString("info"); // temperatureStr=weather.getString("temperature"); // JSONObject info=life.getJSONObject("info"); // JSONArray kongtiao=info.getJSONArray("kongtiao"); // JSONArray yundong=info.getJSONArray("yundong"); // JSONArray ziwaixian=info.getJSONArray("ziwaixian"); // ACStr=kongtiao.getString(0)+" "+kongtiao.getString(1); // sportStr=yundong.getString(0)+" "+yundong.getString(1); // lightStr=ziwaixian.getString(0)+" "+ziwaixian.getString(1); /** * Gson数据解析 */ WheatherBean wheatherBean=new Gson().fromJson(res,WheatherBean.class); String reason=wheatherBean.getReason(); if (reason.equals("参数不正确")){ handler.sendEmptyMessage(1); return; } WheatherBean.ResultBean resultBean=wheatherBean.getResult(); WheatherBean.ResultBean.RealtimeBean realtimeBean=resultBean.getRealtime(); WheatherBean.ResultBean.RealtimeBean.WindBean windBean=realtimeBean.getWind(); String time=realtimeBean.getTime(); WheatherBean.ResultBean.RealtimeBean.WeatherBean weatherBean=realtimeBean.getWeather(); String date=realtimeBean.getDate(); dateStr=time+date; weekStr=realtimeBean.getWeek(); calendarStr=realtimeBean.getMoon(); windpowerStr=windBean.getDirect()+" "+windBean.getPower(); temperatureStr=weatherBean.getTemperature(); weatherStr=weatherBean.getInfo(); WheatherBean.ResultBean.LifeBean lifeBean=resultBean.getLife(); WheatherBean.ResultBean.LifeBean.InfoBean infoBean=lifeBean.getInfo(); List<String> kongtiao=infoBean.getKongtiao(); List<String> yundong=infoBean.getYundong(); List<String> ziwaixian=infoBean.getZiwaixian(); ACStr=kongtiao.get(0)+" "+kongtiao.get(1); sportStr=yundong.get(0)+" "+yundong.get(1); lightStr=ziwaixian.get(0)+" "+ziwaixian.get(1); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python慕遥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值