I attached an LCD on the Raspberry Pi (planned to be a separate article), Sometimes the morning bus is late, sometimes on time I was wondering when to leave the front door, so Odakyu Bus Operation Information To scrape and display.
I scraped it with Beatiiful Soup. With just a CSS selector to get the estimated arrival time It just doesn't work, is it the following power technique? of It has become a very dirty code.
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=[Bus stop to get on]&fromType=1&to=[Get off at the bus stop]&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])
By the way, the calling part is
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)
It's pretty clunky. The estimated time of arrival of the bus is only hours, so If you simply subtract from UNIX time, the number of years will be negative, I only use it anyway, so I divide it.
I think I can write them a little better. .. If you move for the time being, it's divisible.
Recommended Posts