[PYTHON] I tried to get the location information of Odakyu Bus

background

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.

Outline

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.

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

I tried to get the location information of Odakyu Bus
I tried to get the movie information of TMDb API with Python
I tried to visualize the spacha information of VTuber
I want to get the operation information of yahoo route
I tried to get various information from the codeforces API
I tried to get the index of the list using the enumerate function
PhytoMine-I tried to get the genetic information of plants with Python
I tried to touch the API of ebay
I tried to correct the keystone of the image
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
I tried to get the batting results of Hachinai using image processing
I tried to get the authentication code of Qiita API with Python.
I tried to get the RSS of the top song of the iTunes store automatically
I tried to summarize the basic form of GPLVM
I tried to erase the negative part of Meros
[Python] I tried to get Json of squid ring 2
I tried to classify the voices of voice actors
I tried to summarize the string operations of Python
I tried to find the entropy of the image with python
[Horse Racing] I tried to quantify the strength of racehorses
I tried to find the average of the sequence with TensorFlow
I tried to notify the train delay information with LINE Notify
I tried to get Web information using "Requests" and "lxml"
I want to plot the location information of GTFS Realtime on Jupyter! (With balloon)
[Python] I tried to visualize the follow relationship of Twitter
I tried to visualize the characteristics of new coronavirus infected person information with wordcloud
[Machine learning] I tried to summarize the theory of Adaboost
I tried to fight the Local Minimum of Goldstein-Price Function
Keras I want to get the output of any layer !!
I tried to move the ball
I tried to estimate the interval.
I tried to get the information of the .aspx site that is paging using Selenium IDE as non-programming as possible.
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried to make an activity that collectively sets location information
I want to get the name of the function / method being executed
[Linux] I tried to summarize the command of resource confirmation system
I tried to get a database of horse racing using Pandas
I tried to automate the watering of the planter with Raspberry Pi
I tried to build the SD boot image of LicheePi Nano
I looked at the meta information of BigQuery & tried using it
I tried to get a list of AMI Names using Boto3
I tried to get started with Bitcoin Systre on the weekend
I tried to expand the size of the logical volume with LVM
I tried to summarize the frequently used implementation method of pytest-mock
I tried to improve the efficiency of daily work with Python
[Python] I tried to get various information using YouTube Data API!
I tried to visualize the common condition of VTuber channel viewers
I tried the asynchronous server of Django 3.0
I tried to summarize the umask command
I tried to recognize the wake word
I tried to get started with Hy
I tried to summarize the graphical modeling.
I tried to estimate the pi stochastically
I tried to touch the COTOHA API
I tried to make a site that makes it easy to see the update information of Azure
I tried to visualize the age group and rate distribution of Atcoder
I tried transcribing the news of the example business integration to Amazon Transcribe
zoom I tried to quantify the degree of excitement of the story at the meeting
I tried to estimate the similarity of the question intent using gensim's Doc2Vec