趣味で計算流砂水理

趣味で計算流砂水理 Computational Sediment Hydraulics for Fun Learning

数値計算とか河川工学とかプログラミングのことを書いています

MENU

備忘録:pythonでwebスクレイピング:プログラミングの筋トレ

スポンサーリンク


導入

たまにやらないと忘れるので。簡単なスクレイピングの話です。

海上保安庁の潮汐推算のwebページスクレイピングです。

データ公開ページ(例えば、https://www1.kaiho.mlit.go.jp/TIDE/pred2/cgi-bin/TidePredCgi.cgi?area=1603&back=../TidePred/tide_pred/2.htm&btn=ForAreaWindow_Japanese )ですが、 なぜかボタンをクリックするとバグります。

pythonによるwebスクレイピング

pythonでのwebスクレイピングのコツは、

  • seleniumに頼らない。出来るだけbeautifulsoupを使う。
  • Chromeデベロッパーツールでwebサイトをしっかり分析する。

くらいじゃないでしょうか。

それだけ、上のhtml内にタグで数値が埋め込まれているような化石サイトでも、下記のような短いコードでスクレイピングできます。

import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import requests
def getHarr(Area,Area2,year,month,day):
    url = f'https://www1.kaiho.mlit.go.jp/TIDE/pred2/cgi-bin/TidePredCgi.cgi?area={Area}&back=../TidePred/tide_pred/{Area2}.htm&year={year}&month={month}&day={day}&btn=%E6%8E%A8%E3%80%80%E7%AE%97'
    res = requests.get(url)
    soup = BeautifulSoup(res.content, 'html.parser')
    text = [t.get_text() for t in soup.findAll("td")]
    data = text[14:26] + text[40:52]
    # マイナス値の処理
    data = [d.replace(' ','') for d in data]
    return np.array(data, dtype=float)
%%time
Area = 1603
Area2 = 5
sdate = '2023/01/01'
edate = '2023/12/31'

val = [getHarr(Area, Area2, d.year, d.month, d.day) for d in pd.date_range(sdate, edate, freq='D')]
val = np.array(val).flatten()

df = pd.DataFrame(val
             , columns=[Area]
             , index=pd.date_range(sdate, periods=len(val), freq='H')
                 )
CPU times: total: 2min 16s
Wall time: 3min 49s
  • export
df.to_csv('tmp.csv', index_label='time')
  • export
df.plot()

Gist

gistd8b965fd743e0a46716787187dccfc82

Google Colab

※Colabの解説記事はこちら

Open In Colab