天氣資料爬取及分析

2022-09-21 22:12:16 字數 2680 閱讀 7089

而每月的資料,以2023年1月為例,鏈結為:

採用requests,beautifulsoup兩個工具。遍歷12個月份的鏈結,為了防止被遮蔽,每次請求前暫停3秒。

誰知,**可能有個簡單的反爬機制,通過偽造乙個資料報的user-agent資訊,偽裝成瀏覽器請求成功。

爬取後,儲存在json格式的檔案,如下為檔案中部分資料截圖

每一條資料如下格式:['2020-01-01 星期三 ', '5℃', '-7℃', '晴轉多雲', '南風 1級']

求取每月的最高氣溫與最低氣溫的平均值,得出全年氣溫變化,如下所示,由此可見晝夜溫差並不是很大,且全年氣溫較為適宜,四季分明。

統計全年的天氣狀況,並繪製餅圖,如下所示,由於一些天氣狀況較少,所以只展示前八的天氣,由下可見,全年晴天較多(帶來好心情),降水較少,較為乾旱。

統計資料:

餅圖:

import re

import requests

from bs4 import beautifulsoup

import time

from tqdm import tqdm

import json

import collections

import matplotlib.pyplot as plt

plt.rcparams['font.sans-serif']=['simhei']

#共有12個月需要爬取,設定url鏈結中page的引數,其中tqdm用於進度條

year=

for i in tqdm(range(1,13)):

time.sleep(3)

url = ''+str('%02d'%i)+'.html'

# 請求頁面

r = requests.get(url,headers=headers)

html = beautifulsoup(r.text, 'html.parser')

table=html.find_all('ul',)

li=table[0].find_all('li')

month=

for i in li:

div=i.find_all('div')

day=

for j in div:

with open('c:/users/dell/desktop/season.json', 'w', encoding='utf-8') as f:

json.dump(year,f)

with open('c:/users/dell/desktop/season.json', 'r', encoding='utf-8') as f:

year=json.load(f)

print(year)

year_high_temperature=

year_low_temperature =

year_weather=

for month in year:

high_temperature=0

low_temperature = 0

month_weather=

for day in month:

high_day_temperature=int(re.findall(r'-?\d+',day[1])[0])

low_day_temperature = int(re.findall(r'-?\d+', day[2])[0])

high_temperature=high_temperature+high_day_temperature

low_temperature = low_temperature+low_day_temperature

year_weather.extend(month_weather)

plt.title(u'長治市全年每月最高溫與最低溫變化')

plt.xlabel(u'年份')

plt.ylabel(u'溫度')

plt.plot(range(1,13),year_high_temperature,'-o',label=u'最高溫')

plt.plot(range(1,13),year_low_temperature,'-o',label=u'最低溫')

plt.legend(loc = 'upper right')

plt.show()

year_weather=collections.counter(year_weather)

print(year_weather)

weather=

days=

for key,value in year_weather.most_common(8):

print(days)

plt.title(u'長治市全年天氣狀況餅狀圖')

plt.pie(days,labels=weather,autopct='%1.1f%%',shadow=false)

plt.show()

python爬取歷史天氣資料

import requests from requests.exceptions import requestexception from bs4 import beautifulsoup import os import csv import time def get one page url 獲...

Python爬取中國天氣網天氣資料

由於一些需要,想要獲取今天的天氣資料,於是又撿起了python寫了個爬蟲用來獲取中國天氣網上的氣象資料。由於我需要的資料比較簡單,因為我只需要北京地區當天的溫度 最低溫度和最高溫度 和天氣,因此 部分比較簡單,下面就來講講這個爬取的過程。第一步 網頁分析 要進行爬蟲設計,首先得分析網頁的請求過程。首...

Python 爬蟲,爬取歷史天氣資料

先上原始碼 這次用的是beautifulsoup,解析html,非常的便捷 import datetime import pandas as pd import re import requests import time from bs4 import beautifulsoup headers ...