---
# System prepended metadata

title: 社課1-5_Selenium自動網站登入實作

---

輕鬆學習 Python |從基礎到應用，成為初級資料分析師

# 網頁自動登入系統
環境: Spyder

## 步驟:

### 1. 環境建置層 
```
#!/usr/bin/env python3
import selenium
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

def automate_ticket_login():
    print("正在初始化瀏覽器設定 (Linux/Headless mode)...")
    
    # --- 1. 設定 Chrome 選項 (維持 Linux 穩定性) ---
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')                # 無頭模式
    options.add_argument('--no-sandbox')              # 解決 Linux 權限問題
    options.add_argument('--disable-dev-shm-usage')   # 解決資源共享問題
    options.add_argument('--disable-gpu')             
    options.add_argument('--window-size=1920,1080')   
    options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36')

    service = Service(ChromeDriverManager().install())
```
### 2.導航與定位
```
    driver = None
    try:
        driver = webdriver.Chrome(service=service, options=options)
        
        print("1. 前往購票網站首頁...")
        driver.get("https://tickets.kje-event.com.tw/booking/86891059/member/login/68c0da4f39ac931793cc89be-%E6%9C%83%E5%93%A1%E5%85%8D%E8%B2%BB%E9%99%90%E9%87%8F%E9%96%80%E7%A5%A8")
        
        wait = WebDriverWait(driver, 15)
```
### 3.互動輸入
```
        print("2. 輸入登入資訊 (使用 ID: inputEmail / inputPassword)...")
        
        # 等待 Email 欄位 (ID: inputEmail)
        email_input = wait.until(EC.visibility_of_element_located((By.ID, "inputEmail")))
        email_input.clear()
        email_input.send_keys("自己的帳號@gmail.com")

        # 輸入密碼 (ID: inputPassword)
        password_input = driver.find_element(By.ID, "inputPassword")
        password_input.clear()
        password_input.send_keys("自己的密碼")
        
        
        print("擷取登入前畫面...")
        filename = "login_before.png"
        driver.save_screenshot(filename)

        print("4. 點擊登入按鈕...")
        # 通常登入按鈕會在密碼框附近，或是有 type='submit'
        try:
            # 嘗試尋找 "登入" 按鈕，若無 ID 則使用通用特徵
            login_btn = driver.find_element(By.XPATH, "//button[contains(text(), '登入')] | //input[@type='submit'] | //button[@type='submit']")
            driver.execute_script("arguments[0].click();", login_btn)
        except:
            # 如果找不到按鈕，嘗試對密碼框按 Enter
            print("   -> 找不到明確的登入按鈕，嘗試按 Enter 鍵送出...")
            from selenium.webdriver.common.keys import Keys
            password_input.send_keys(Keys.RETURN)

```
### 4.驗證與存證
```
        print("5. 等待 10 秒 (資料處理中)...")
        time.sleep(10)

        print("擷取登入後畫面...")
        filename = "login_success_10s.png"
        driver.save_screenshot(filename)
        print(f"成功！截圖已儲存為: {filename}")
```
### 5.異常處理
```
    except Exception as e:
        print(f"發生錯誤: {e}")
        if driver:
            driver.save_screenshot("error_debug_specific.png")
            print("已儲存錯誤截圖: error_debug_specific.png")
            # 印出當前網址，確認是否跳轉
            print(f"當前網址: {driver.current_url}")
            
    finally:
        if driver:
            print("關閉瀏覽器...")
            driver.quit()

if __name__ == "__main__":
    automate_ticket_login()
```