YouBike 還車站

  1. 下面這則程式可以幫我們查到兩個 YouBike 還車站的車位狀況:
    # Kaohsiung YouBike
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.keys import Keys
    import time
    
    def startChrome():
        import google_colab_selenium as gs
        chrome = gs.Chrome()    
        return chrome
    
    # Choose Kaohsiung City
    def chooseKaohsiungCity(chrome):
        city = chrome.find_element(By.ID, value="stations-select-area")
        city.click()
        city.send_keys(Keys.END)
        city.send_keys(Keys.ARROW_UP)
        city.send_keys(Keys.ENTER)
    
    def getStationInfo(chrome, stationName):
        # Input Station Name
        station = chrome.find_element(By.ID, value="stationListSearchInput")
        station.click()
        from selenium.webdriver import ActionChains
        ActionChains(chrome).key_down(Keys.SHIFT).send_keys(Keys.HOME).perform()
        station.send_keys(Keys.DELETE)
        #station.clear()
        station.send_keys(stationName)
        station.send_keys(Keys.ENTER)
        # Retrieve Station Information
        time.sleep(5.0)
        tbl = chrome.find_element(By.XPATH, "//ul[@class='item-inner2']")
        stations = []
        aList = tbl.text.split('\n')
        for i in range(0, len(aList), 5):
            stations.append([*aList[i:i+5]])
        return stations
    
    def showStationInfo(stations):
        fmt = "{}\t{}\t{:20}\t{}\t{}"
        print(fmt.format('縣市', '區域', '站點名稱', '可借車輛', '可停空位'))
        for station in stations:
            if len(station) != 5: continue
            print(fmt.format(*station))
    
    chrome = startChrome()
    chrome.implicitly_wait(0.5) # This method only needs to be called one time per session.
    url = "https://www.youbike.com.tw/region/main/stations/list/"
    chrome.get(url)
    chooseKaohsiungCity(chrome)
    
    stationName = '英雄'
    results = getStationInfo(chrome, stationName) 
    showStationInfo(results)
    
    chrome.quit()
  2. 試修改以上程式,讓它可以一口氣幫我們查出高雄女中週遭六個還車站的資訊。
  3. 程式輸出結果大概長這樣:
    縣市 區域    站點名稱                        可借車輛 可停空位
    高雄市  前金區  高雄女中                        0       0
    高雄市  前金區  高雄女中(英雄路口)              4       26
    高雄市  苓雅區  高雄國軍英雄館                  2       22
    高雄市  前金區  五福成功一路口                  0       28
    高雄市  前金區  光復三市中路口                  22      0
    高雄市  苓雅區  海邊新田路口                    13      10