以下程式可幫我們預約圖書館的自習座位。
(你其實可以把帳號、密碼、座位優先序也都事先寫在程式中,然後指定時間要它自動幫你預約。
這裡仍以互動方式進行示範。)
# 晚自習預約管理系統
import getpass
txtUser = input("User ID? ")
txtPw = getpass.getpass("Password? ")
import google_colab_selenium as gs
chrome = gs.Chrome()
from selenium.webdriver.common.by import By
# 1. Login
url = "http://163.16.245.4/studying/login.aspx"
chrome.get(url)
user = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_txt_userMemory")
pw = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_txt_passWord")
button = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_btn_check")
user.send_keys(txtUser)
pw.send_keys(txtPw)
button.click()
chrome.implicitly_wait(0.5) # This method only needs to be called one time per session.
# 2. Show News
#print(chrome.page_source)
button = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_Btn_confirm")
button.click()
# 3. 申請
radio = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_RadioButtonList_join_0")
radio.click()
# 4. 同意
button = chrome.find_element(By.ID, value="ContentPlaceHolder1_Btn_agree")
button.click()
# 5. 申請 (不知為什麼還要再申請一次)
radio = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_RadioButtonList_join_0")
radio.click()
# 6. 依日期選座位
button = chrome.find_element(by=By.ID, value="ContentPlaceHolder1_ByDate")
button.click()
# 7. 選日期
# https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath
tbl = chrome.find_element(By.ID, value="ContentPlaceHolder1_CalA")
d = tbl.find_element(By.XPATH, "//a[@title='5月29日']")
d.click()
# 8. 選時段 (即使只有一個時段可選)
radio = chrome.find_element(By.ID, value="ContentPlaceHolder1_RadioButtonList1_0")
radio.click()
# 9. 選擇座位
tbl = chrome.find_element(By.ID, value="ContentPlaceHolder1_seat")
choice = input("請選擇座位 (e.g. J19) -- ")
seat = tbl.find_element(By.XPATH, "//input[@name='ctl00$ContentPlaceHolder1${}']".format(choice))
value = seat.get_attribute("value")
if value != choice: # 若已被預約,value會顯示預約人的名字
print("Sorry! 這位子已被人預約。")
else:
seat.click()
# 10. 確認
button = chrome.find_element(By.XPATH, "//input[@name='ctl00$ContentPlaceHolder1$confirm']")
button.click()
print("{} - 預約成功!".format(choice))