小田急バスの位置情報をスクレイピング

qiita.com

import datetime
import requests
from bs4 import BeautifulSoup

# timedeltaを%H:%Mに変換
def time_str(t):
    return ':'.join(str(t).split(':')[:2])

if __name__ == "__main__":

    出発 = ""
    到着 = ""

    url = f"https://odakyu.bus-navigation.jp/wgsys/wgs/bus.htm?tabName=searchTab&selectedLandmarkCatCd=&from={出発}&fromType=1&to={到着}&toType=1&locale=ja&fromlat=&fromlng=&tolat=&tolng=&fromSignpoleKey=&routeLayoutCd=&bsid=1&fromBusStopCd=&toBusStopCd=&mapFlag=false&existYn=N&routeKey=&nextDiagramFlag=&diaRevisedDate=&timeTableDirevtionCd="

    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
    }

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

    r.raise_for_status()

    soup = BeautifulSoup(r.content, "html5lib")

    s = soup.select_one('div[style="background-color: gold;"] > table:nth-of-type(2) > tbody > tr:nth-of-type(2) > td:nth-of-type(2)')

    if s:
        _, d = s.get_text(strip=True).split()
        h, m = map(int, d.split(":"))

        # 発車予測
        td_dep = datetime.timedelta(hours=h, minutes=m)

        # 現在の時間
        dt_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
        td_now = datetime.timedelta(hours=dt_now.hour, minutes=dt_now.minute)

        td = time_str(td_dep - td_now)

        print(f"Next bus in {td}")
        print(f"Next bus@ {d}")

    else:
        print("接近しているバスはありません。")