1
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?

More than 5 years have passed since last update.

小田急バスの位置情報を取得してみた

Posted at

背景

ラズベリーパイでLCDを付けましたが(別記事にする予定)、
朝のバスが遅れたり、たまにオンタイムだったりと
いつ玄関を出るか悩んでいたので、
小田急バス運行情報
をスクレイピングして、表示することに。

概略

Beatiiful Soupを使って、スクレイピングしました。
到着予想時刻をとるために、単なるCSSセレクターでは
どうしてもうまくいかず、以下のような力技?の
とても汚いコードになってしまいました。

コード

from bs4 import BeautifulSoup as BS
import urllib.request as req

def busstop():
    url="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="
    res=req.urlopen(url)
    soup=BS(res,"html.parser")
    #data=soup.select("#buslist > div > div>table:nth-of-type(2)")
    result=[]

    table=soup.select_one("table:nth-of-type(2)")

    tr_list=table.find_all("tr")

    current=0
    for tr in tr_list:
        result_row=[]
        td_list=tr.find_all(["td","th"])
        if current<4:
            for td in td_list:
                cell = td.get_text()
                result_row.append(cell)
                if current==3:
                    result_list=[]
                    result_list=result_row
                current=current+1
        else:
            pass

    final_arrange_list=[]

    if final_arrange_list==None:
       return("NA")
    else:
       final_arrange_list=result_list[1].split(' ')
       return(final_arrange_list[1])
       print(final_arrange_list[1])

ちなみに呼び出し部は

   bustime_dt=datetime.strptime(busstop(),'%H:%M')
   nowtime_dt=datetime.strptime(time.ctime(time.time()),'%a %b %d %H:%M:%S %Y')
   next_bus_time=bustime_dt-nowtime_dt
   payload7="Next bus in "+str(next_bus_time.seconds/60)
   payload8="Next bus@ "+str(busstop())
   print(payload7)
   print(payload8) 
   lcd_string(payload7, LCD_LINE_1)
   lcd_string(payload8, LCD_LINE_2)

となかなか不格好です。
バスの到着予想時刻には、時間分しかないので、
単純にUNIX時間から引くと、年数がマイナスになるのですが、
どうせ分しか使わないので、割り切り。

いずれももう少しうまく書けるのだろうけれど。。
とりあえず動けばということで、割り切り。

1
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
1
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?