核心 API 參考
本章節介紹在候鳥環境中使用 Selenium 時最常用的 API 方法,幫助您構建穩健的自動化代碼。
1. 元素定位 (Find Elements)
Selenium 4 推薦使用 By 模塊進行定位。
python
from selenium.webdriver.common.by import By
# 常用定位方式
element = driver.find_element(By.ID, "login-btn")
element = driver.find_element(By.NAME, "username")
element = driver.find_element(By.CSS_SELECTOR, ".class-name")
element = driver.find_element(By.XPATH, "//button[text()='提交']")2. 自動等待 (Explicit Waits)
為了防止網速慢導致的腳本崩潰,強烈建議不使用 time.sleep(),而是使用 WebDriverWait。
python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 等待元素出現並可點擊 (最長等待 10 秒)
wait = WebDriverWait(driver, 10)
btn = wait.until(EC.element_to_be_clickable((By.ID, "submit")))
btn.click()3. Cookie 管理
候鳥環境會自動持久化 Cookie,但在自動化流程中,您可能需要手動操作。
python
# 獲取當前環境所有 Cookie
cookies = driver.get_cookies()
# 添加自定義 Cookie (通常用於免密登錄)
driver.add_cookie({
"name": "session_id",
"value": "abs123...",
"domain": ".amazon.com"
})
# 刪除所有 Cookie
driver.delete_all_cookies()4. 特徵隱藏與規避 (防檢測)
雖然候鳥已處理了大部分指紋,但在 Selenium 調用時,某些網站會檢測 cdc_ 標識。候鳥的定制內核已對此進行了深度優化,但您仍可配合以下代碼:
python
# 隱藏 Selenium 自動化標識 (候鳥內核已默認優化)
chrome_options.add_argument("--disable-blink-features=AutomationControlled")5. 其它常用操作
driver.get(url): 跳轉頁面。driver.save_screenshot("page.png"): 截取當前頁面。driver.execute_script("window.scrollTo(0, 500)"): 執行自定義 JS 腳本(如滾動)。driver.switch_to.frame("iframe_id"): 切換到 IFrame 框架。
IMPORTANT
提示: 雖然 Selenium 支持模擬行為,但請勿使用過高的並發頻率,以免觸發網站對 IP 的異常訪問監控。
TIP
掌握了核心 API?在 實戰示例 中,您將看到如何將這些 API 組合起來解決真實業務問題。
