0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

気象庁のHPをスクレイピングして1時間毎の気象データをえるコード

Posted at

1時間ごとの気象データを得るためのコード
こちらを参考にさせていただきました、ありがとうございました。
https://qiita.com/Cyber_Hacnosuke/items/122cec35d299c4d01f10

place_codeA = [44, 62, 14, 17, 20, 31, 32, 33, 35, 34, 36, 54, 56, 55, 48, 41, 57, 42, 43, 40, 52, 51, 49, 45, 53, 50, 46, 68, 69, 61, 60, 67, 66, 63, 65, 64, 73, 72, 74, 71, 81, 82, 85, 83, 84, 86, 88, 87, 91]
place_codeB = [47662, 47772, 47412, 47409, 47417, 47575, 47582, 47584, 47588, 47590, 47595, 47604, 47605, 47607, 47610, 47615, 47616, 47624, 47626, 47629, 47632, 47636, 47638, 47648, 47651, 47656, 47670, 47741, 47746, 47759, 47761, 47765, 47768, 47770, 47777, 47780, 47887, 47891, 47893, 47895, 47762, 47807, 47813, 47815, 47817, 47819, 47827, 47830, 47936]
place_name = ["東京", "大阪", "札幌", "網走", "帯広", "青森", "秋田", "盛岡", "山形", "仙台", "福島", "新潟", "金沢", "富山", "長野", "宇都宮", "福井", "前橋", "熊谷", "水戸", "岐阜", "名古屋", "甲府", "銚子", "津", "静岡", "横浜", "松江", "鳥取", "京都", "彦根", "広島", "岡山", "神戸", "和歌山", "奈良", "松山", "高松", "高知", "徳島", "下関", "福岡", "佐賀", "大分", "長崎", "熊本", "鹿児島", "宮崎", "沖縄"]   

import requests
from bs4 import BeautifulSoup
import csv
from calendar import monthrange  # monthrangeをインポート

# 時間ごとのデータを取得するためのURL
base_url = "https://www.data.jma.go.jp/stats/etrn/view/hourly_s1.php?prec_no=%s&block_no=%s&year=%s&month=%s&day=%s&view=p1"

# 取ったデータをfloat型に変えるやつ。(データが取れなかったとき気象庁は"/"を埋め込んでいるから0に変える)
def str2float(str):
    try:
        return float(str)
    except:
        return 0.0

if __name__ == "__main__":
    # 都市を網羅します
    for place in place_name:
        All_list = [['年月日', '時間', '陸の平均気圧(hPa)', '海の平均気圧(hPa)', '降水量(mm)', '平均気温(℃)', '平均湿度(%)', '平均風速(m/s)', '日照時間(h)']]
        print(place)
        index = place_name.index(place)

        # 2022年11月から2023年12月までのデータを取得
        for year in range(2022, 2024):  # 2022年と2023年を網羅
            # 2022年11月から2023年12月まで
            for month in range(11, 13) if year == 2022 else range(1, 13):  # 2022年11月から2023年12月
                # 月ごとの日数を取得
                _, last_day = monthrange(year, month)
                
                for day in range(1, last_day + 1):  # 月の日数を正しく設定
                    # URLに年、月、日を埋め込んでリクエストを送信
                    url = base_url % (place_codeA[index], place_codeB[index], year, month, day)
                    print(url)  # 確認用にURLを表示

                    r = requests.get(url)
                    r.encoding = r.apparent_encoding
                    soup = BeautifulSoup(r.text, 'html.parser')

                    # 時間ごとのデータ行を取得
                    rows = soup.findAll('tr', class_='mtx')[2:]  # データ部分を取得
                    for row in rows:
                        data = row.findAll('td')
                        rowData = []
                        rowData.append(f"{year}/{month}/{day}")  # 年月日
                        rowData.append(f"{data[0].string}")  # 時間
                        rowData.append(str2float(data[1].string))  # 陸の平均気圧
                        rowData.append(str2float(data[2].string))  # 海の平均気圧
                        rowData.append(str2float(data[3].string))  # 降水量
                        rowData.append(str2float(data[4].string))  # 平均気温
                        rowData.append(str2float(data[7].string))  # 平均湿度
                        rowData.append(str2float(data[8].string))  # 平均風速
                        rowData.append(str2float(data[10].string))  # 日照時間
                        All_list.append(rowData)

        # 都市ごとにデータをファイルを新しく生成して書き出す。(csvファイル形式。名前は都市名)
        with open(f"{place}__hourly_2022_2023.csv.csv", 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerows(All_list)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?