下面這則程式可以幫我們查到兩個 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()