python爬取一年天气数据

因为有些分数问我怎么直接爬取一年的天气,并做数据分析,今天我就来了

1.爬取2021年一年的数据

首先,我们需要找到一个能够提供天气数据的网站。这里我们选择了中国天气网(【惠州历史天气】惠州历史天气预报_惠州历史天气预报记录查询-历史天气查询网 (tianqi.com)

导出相应的包

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
from pandas import Series, DataFrame

2.进行伪装

headers = {
    'Host': 'lishi.tianqi.com',
    'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36 Edg/112.0.1722.58'
}

3.抓取一年天气数据

url_base = 'https://lishi.tianqi.com/huizhou/2021{}.html' # 惠州 2021年天气
data_all = []
for month in range(1, 13):
    url = url_base.format(str(month).zfill(2))
    res = requests.get(url, headers=headers)
    res.encoding = 'utf-8'
    html = BeautifulSoup(res.text, 'html.parser')
    tian_three = html.find("div", {"class": "tian_three"})
    lishi = tian_three.find_all("li")
    for i in lishi:
        lishi_div = i.find_all("div")
        data = []
        for j in lishi_div:
            data.append(j.text)
        data_all.append(data)

4.数据存储

在数据存储前,对数据进行处理,便于后期的数据分析。将上面的“当天信息”字段拆分为“日期”和“星期”两个字段,“风向信息”也是如此。最后,将数据保存为csv文件中。

weather = pd.DataFrame(data_all)
weather.columns = ["当日信息", "最高气温", "最低气温", "天气", "风向信息"]
weather_shape = weather.shape

weather['当日信息'].apply(str)
result = DataFrame(weather['当日信息'].apply(lambda x: Series(str(x).split(' '))))
result = result.loc[:, 0:1]
result.columns = ['日期', '星期']
weather['风向信息'].apply(str)
result1 = DataFrame(weather['风向信息'].apply(lambda x: Series(str(x).split(' '))))
result1 = result1.loc[:, 0:1]
result1.columns = ['风向', '级数']
weather = weather.drop(columns='当日信息')
weather = weather.drop(columns='风向信息')
weather.insert(loc=0, column='日期', value=result['日期'])
weather.insert(loc=1, column='星期', value=result['星期'])
weather.insert(loc=5, column='风向', value=result1['风向'])
weather.insert(loc=6, column='级数', value=result1['级数'])
weather.to_csv("惠州2021年天气.csv", encoding="utf_8")

5.数据分析

注:数据分析用的是惠州2021年的天气数据,如下图

 

 读取惠州2021年天气情况并转化为图形

# 数据处理
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
 
 
weather['最高气温'] = weather['最高气温'].map(lambda x: int(x.replace('℃', '')))
weather['最低气温'] = weather['最低气温'].map(lambda x: int(x.replace('℃', '')))
 
dates = weather['日期']
highs = weather['最高气温']
lows = weather['最低气温']
 
# 画图
 
fig = plt.figure(dpi=128, figsize=(10, 6))
 
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
 
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.2)
# 图表格式
# 设置图标的图形格式
plt.title('2023惠州2021年天气情况', fontsize=24)
plt.xlabel('', fontsize=6)
fig.autofmt_xdate()
plt.ylabel('气温', fontsize=12)
plt.tick_params(axis='both', which='major', labelsize=10)
# 修改刻度
plt.xticks(dates[::5])
# 显示
plt.show()

因为数据量下面代表日期比较多,所以比较乱一点

  • 3
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

梦幻编织者

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

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

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

打赏作者

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

抵扣说明:

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

余额充值