DeepSeek 整合至網頁版登入的多標籤瀏覽器自動化腳本

在日常的網頁操作中,管理多個需要登入的網站標籤往往效率低下,尤其當登入過程涉及動態資訊生成或複雜邏輯判斷時。本教程將引導您如何結合 DeepSeek 的強大語言模型能力與 Selenium WebDriver 的瀏覽器自動化功能,創建一個能夠處理多標籤網頁登入的自動化腳本,從而顯著提升操作效率。

想像一個場景:您需要登入多個內部系統,其中每個系統的登入流程可能略有不同,甚至某些欄位需要根據上下文動態生成資訊。透過整合 DeepSeek API,我們能夠讓腳本具備理解、生成與判斷的能力,不再僅僅是機械地執行預設步驟。

DeepSeek API 整合基礎

DeepSeek API 提供了一系列強大的語言模型,可以協助我們處理文本生成、理解與邏輯判斷等任務。在多標籤自動化登入的場景中,DeepSeek 可以扮演以下角色:

  • 生成登入憑證: 當您需要為測試環境創建臨時用戶名或密碼時。
  • 解析登入提示: 某些網站的登入頁面可能包含動態的文字提示或安全問題,DeepSeek 可以理解這些提示並生成相應的回答。
  • 輔助決策: 當登入流程有多個分支(例如,選擇不同的登入方式),DeepSeek 可以根據當前頁面內容提供最佳操作建議。

要開始使用 DeepSeek API,您需要:

  1. 獲取 API Key: 訪問 DeepSeek 平台 (例如 chat.deepseek.com 上的 API 設定頁面) 申請您的個人 API Key。請務必妥善保管此 Key,切勿直接硬編碼在公開代碼中。
  2. 選擇模型: DeepSeek 提供多種模型,例如 deepseek-chat 或 deepseek-coder 等。對於本教程的登入輔助任務,deepseek-chat 通常是足夠且高效的選擇。

以下是一個簡單的 Python 函數,展示如何通過 requests 庫調用 DeepSeek API 進行文本生成:

import requests
import json
import os

def get_deepseek_response(prompt_text, api_key):
    """
    透過 DeepSeek API 獲取回應。
    """
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    payload = {
        "model": "deepseek-chat",  # 您可以根據需求選擇其他模型
        "messages": [
            {"role": "user", "content": prompt_text}
        ],
        "temperature": 0.7, # 控制生成文本的隨機性
        "max_tokens": 150 # 最大生成字符數
    }
    
    try:
        response = requests.post("https://api.deepseek.com/chat/completions", headers=headers, json=payload)
        response.raise_for_status() # 對於 4xx 或 5xx 的回應拋出 HTTPError
        data = response.json()
        return data["choices"][0]["message"]["content"].strip()
    except requests.exceptions.RequestException as e:
        print(f"DeepSeek API 請求失敗: {e}")
        return None
    except KeyError as e:
        print(f"DeepSeek API 回應格式錯誤: {e}, 回應: {response.text}")
        return None

# 範例使用
# DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") # 從環境變量獲取更安全
# if DEEPSEEK_API_KEY:
#     generated_username = get_deepseek_response("生成一個獨特的測試用戶名和一個強密碼,用逗號分隔。", DEEPSEEK_API_KEY)
#     print(f"生成的用戶名和密碼: {generated_username}")

設置開發環境

在開始編寫自動化腳本之前,我們需要配置好所需的開發環境。本教程將使用 Python 語言與 Selenium WebDriver。

  1. 安裝 Python: 確保您的系統已安裝 Python 3.8 或更高版本。您可以從 python.org 下載。

  2. 安裝必要的 Python 庫:

    • selenium:用於瀏覽器自動化。
    • requests:用於與 DeepSeek API 進行 HTTP 通信。

    在終端機中執行以下命令安裝:

    pip install selenium requests
    
  3. 下載 WebDriver: Selenium 需要一個 WebDriver 來與您的瀏覽器進行交互。常用的瀏覽器有 Chrome、Firefox 和 Edge。

    將下載的 WebDriver 可執行文件放置在系統 PATH 中,或指定其在腳本中的路徑。

    瀏覽器自動化腳本開發環境設定

網頁多標籤操作核心邏輯

Selenium 提供了強大的功能來操控瀏覽器標籤頁。理解如何開啟、切換和關閉標籤頁是實現多標籤自動化的關鍵。

  • 初始化 WebDriver:

    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
    import time
    
    # 設置 WebDriver 路徑 (如果沒有加入系統 PATH)
    # service = Service(executable_path="/path/to/chromedriver")
    # driver = webdriver.Chrome(service=service)
    
    # 更簡潔的初始化方式,假設 WebDriver 在 PATH 中
    driver = webdriver.Chrome()
    driver.maximize_window() # 最大化窗口以確保元素可見
    
  • 開啟新標籤頁:

    driver.execute_script("window.open('');") # 執行 JavaScript 開啟新標籤
    
  • 切換標籤頁: 每個標籤頁都有一個唯一的窗口句柄(window handle)。您可以通過 driver.window_handles 獲取所有句柄列表。

    window_handles = driver.window_handles
    # 切換到第一個標籤頁 (通常是原始標籤)
    driver.switch_to.window(window_handles[0])
    # 切換到第二個標籤頁
    driver.switch_to.window(window_handles[1])
    
  • 定位元素: 使用 find_element() 方法結合不同的定位策略(ID, Name, XPath, CSS Selector 等)來找到網頁上的元素。

    # 範例:通過 ID 定位用戶名輸入框
    username_field = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "username"))
    )
    # 範例:通過 XPath 定位登入按鈕
    login_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '登入')]"))
    )
    

    這裡使用了 WebDriverWait 和 expected_conditions 來實現顯式等待,確保元素在操作前已經加載並可用,這比簡單的 time.sleep() 更可靠。

DeepSeek 輔助登入資料生成與填寫

DeepSeek API 的集成讓我們的自動化腳本更加智能。它可以在登入過程中動態生成或解析所需的資訊。

情景範例: 假設某個登入頁面會根據日期生成一個特殊的「安全碼提示」,用戶需要輸入一個基於該提示的答案。或者,我們需要為每次測試生成一個唯一的、符合特定模式的用戶名。

  1. 從網頁中提取資訊: 使用 Selenium 獲取頁面上的動態文本。

    # 假設頁面上有一個元素顯示了安全碼提示
    try:
        security_prompt_element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "security-prompt-text"))
        )
        security_prompt = security_prompt_element.text
        print(f"獲取到安全碼提示: {security_prompt}")
    except:
        security_prompt = "無特殊安全提示"
        print("未檢測到特殊安全碼提示。")
    
  2. 向 DeepSeek 請求生成或解析: 將提取到的資訊作為 DeepSeek API 的 prompt_text。

    DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY_FOR_AUTOMATION") 
    if not DEEPSEEK_API_KEY:
        print("錯誤:DeepSeek API Key 未設定。請在環境變量中設定 'DEEPSEEK_API_KEY_FOR_AUTOMATION'。")
        exit() # 終止腳本
        
    deepseek_prompt = f"根據以下提示,生成一個合適的登入答案或臨時用戶名:'{security_prompt}'。如果需要生成用戶名,請格式化為 'test_user_YYYYMMDD_HHMMSS'。如果是回答,請直接給出簡短答案。"
    
    deepseek_response = get_deepseek_response(deepseek_prompt, DEEPSEEK_API_KEY)
    
    if deepseek_response:
        print(f"DeepSeek 生成的回應: {deepseek_response}")
        # 這裡可以根據 DeepSeek 的回應內容進一步解析是用戶名還是答案
        # 簡單處理為直接填入
        generated_data = deepseek_response
    else:
        generated_data = "預設用戶名或錯誤" # 提供一個回退值
    

    DeepSeek 整合自動化流程圖解

  3. 將 DeepSeek 生成的數據注入 Selenium: 將 DeepSeek 生成的 generated_data 填入相應的輸入框。

    try:
        input_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "dynamic-input-field"))
        )
        input_field.send_keys(generated_data)
        print(f"成功將 '{generated_data}' 填入動態輸入框。")
    except Exception as e:
        print(f"填寫動態輸入框失敗: {e}")
    

實作:多標籤自動化登入範例

現在,我們將以上所有部分整合起來,創建一個模擬登入兩個不同網站的腳本,其中一個網站的登入信息可能需要 DeepSeek 輔助。

import requests
import json
import os
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 datetime import datetime

# --- DeepSeek API 輔助函數 (與上面相同) ---
def get_deepseek_response(prompt_text, api_key):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "user", "content": prompt_text}
        ],
        "temperature": 0.7,
        "max_tokens": 150
    }
    
    try:
        response = requests.post("https://api.deepseek.com/chat/completions", headers=headers, json=payload)
        response.raise_for_status()
        data = response.json()
        return data["choices"][0]["message"]["content"].strip()
    except requests.exceptions.RequestException as e:
        print(f"DeepSeek API 請求失敗: {e}")
        return None
    except KeyError as e:
        print(f"DeepSeek API 回應格式錯誤: {e}, 回應: {response.text}")
        return None

# --- 主要自動化腳本 ---
def automate_multi_tab_login(deepseek_api_key):
    # 假設 WebDriver 在 PATH 中,或指定 executable_path
    driver = webdriver.Chrome()
    driver.maximize_window()

    try:
        # --- 第一個登入標籤頁 ---
        print("\n--- 處理第一個登入頁面 (無需 DeepSeek) ---")
        driver.get("https://example.com/login1") # 替換為您的第一個登入頁面 URL
        # 等待頁面加載
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "username1"))
        )

        # 填寫登入資訊
        driver.find_element(By.ID, "username1").send_keys("user_static_01")
        driver.find_element(By.ID, "password1").send_keys("password_static_01")
        driver.find_element(By.XPATH, "//button[text()='Login 1']").click()
        
        # 驗證登入是否成功 (可以檢查 URL 或頁面元素)
        WebDriverWait(driver, 15).until(
            EC.url_contains("/dashboard1") # 替換為登入成功後的 URL 片段
        )
        print("成功登入第一個網站。")
        time.sleep(2) # 稍作等待

        # --- 第二個登入標籤頁 (需要 DeepSeek 輔助) ---
        print("\n--- 處理第二個登入頁面 (DeepSeek 輔助) ---")
        # 開啟一個新標籤頁
        driver.execute_script("window.open('');")
        # 切換到新標籤頁 (通常是最後一個)
        driver.switch_to.window(driver.window_handles[-1])
        
        driver.get("https://example.com/login2") # 替換為您的第二個登入頁面 URL
        # 等待頁面加載,並檢查是否有動態提示
        security_prompt = "無特殊安全提示"
        try:
            # 假設有一個元素顯示了需要 DeepSeek 解析的提示文本
            prompt_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "dynamic-security-prompt"))
            )
            security_prompt = prompt_element.text
            print(f"獲取到動態安全提示: {security_prompt}")
        except:
            print("未檢測到第二個網站的動態安全提示,將請求 DeepSeek 生成默認用戶名。")

        # 使用 DeepSeek 生成用戶名和密碼
        prompt_text_to_deepseek = f"根據以下提示,生成一個用於網站登入的唯一用戶名和一個強密碼,用逗號分隔。提示:'{security_prompt}'。用戶名格式為 'test_deepseek_YYYYMMDDHHMMSS'。"
        deepseek_credentials_str = get_deepseek_response(prompt_text_to_deepseek, deepseek_api_key)

        if deepseek_credentials_str:
            print(f"DeepSeek 生成的登入憑證字串: {deepseek_credentials_str}")
            try:
                username, password = deepseek_credentials_str.split(',', 1) # 只分割一次
                username = username.strip()
                password = password.strip()
            except ValueError:
                print("DeepSeek 回應格式不符,使用預設憑證。")
                username = f"deepseek_user_{datetime.now().strftime('%Y%m%d%H%M%S')}"
                password = "DeepSeekPassword@123"
        else:
            print("未能從 DeepSeek 獲取憑證,使用預設值。")
            username = f"deepseek_user_{datetime.now().strftime('%Y%m%d%H%M%S')}"
            password = "DeepSeekPassword@123"

        # 填寫登入資訊
        username_field_2 = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "username2")) # 替換為第二個網站的用戶名 ID
        )
        password_field_2 = driver.find_element(By.ID, "password2") # 替換為第二個網站的密碼 ID
        login_button_2 = driver.find_element(By.XPATH, "//button[text()='Login 2']") # 替換為第二個網站的登入按鈕 XPath

        username_field_2.send_keys(username)
        password_field_2.send_keys(password)
        login_button_2.click()

        WebDriverWait(driver, 15).until(
            EC.url_contains("/dashboard2") # 替換為第二個網站登入成功後的 URL 片段
        )
        print(f"成功登入第二個網站,使用用戶名: {username}")
        time.sleep(2)

        # 您可以切換回第一個標籤頁繼續操作
        print("\n--- 切換回第一個標籤頁 ---")
        driver.switch_to.window(driver.window_handles[0])
        print(f"當前 URL: {driver.current_url}")
        time.sleep(3) # 留出時間觀察

    except Exception as e:
        print(f"自動化腳本執行失敗: {e}")
    finally:
        print("\n--- 自動化完成,關閉瀏覽器 ---")
        driver.quit()

if __name__ == "__main__":
    # 從環境變量獲取 DeepSeek API Key,安全性更高
    # 在運行前,請設置環境變量,例如:
    # export DEEPSEEK_API_KEY_FOR_AUTOMATION="YOUR_DEEPSEEK_API_KEY" (Linux/macOS)
    # $env:DEEPSEEK_API_KEY_FOR_AUTOMATION="YOUR_DEEPSEEK_API_KEY" (PowerShell)
    deepseek_key = os.getenv("DEEPSEEK_API_KEY_FOR_AUTOMATION")
    
    if not deepseek_key:
        print("錯誤:DeepSeek API Key 未設定。請在環境變量中設定 'DEEPSEEK_API_KEY_FOR_AUTOMATION'。")
    else:
        print("DeepSeek API Key 已讀取。開始執行自動化腳本...")
        automate_multi_tab_login(deepseek_key)

請注意:

  • 範例中的 https://example.com/login1、https://example.com/login2 以及所有元素定位器 (如 username1, password1, Login 1 按鈕文本等) 都需要替換為您實際目標網站的 URL 和 HTML 元素 ID/XPath/Class。
  • 這個腳本假定 DeepSeek 返回的用戶名和密碼以逗號分隔。如果 DeepSeek 返回的格式不同,您需要調整解析邏輯。
  • 為 DeepSeek API Key 設置環境變量 DEEPSEEK_API_KEY_FOR_AUTOMATION 是推薦的安全性做法。

最佳實踐與注意事項

開發自動化腳本時,應考慮以下最佳實踐和潛在問題:

  1. 錯誤處理: 腳本應包含健壯的錯誤處理機制 (try-except 區塊),以應對網頁加載失敗、元素定位錯誤或 DeepSeek API 調用失敗等情況。
  2. 等待策略: 避免使用硬編碼的 time.sleep(),除非是為了觀察。應優先使用 Selenium 的顯式等待 (WebDriverWait 與 expected_conditions),這能讓腳本更穩定地等待元素出現或滿足特定條件。
  3. 避免被檢測/封鎖: 頻繁且高速的自動化操作可能被網站識別為機器人行為。
    • 增加隨機延遲: 在操作之間加入隨機時間間隔 (time.sleep(random.uniform(1, 3)))。
    • 模擬真實用戶行為: 例如,模擬鍵盤輸入時的延遲 (driver.find_element(...).send_keys("text", delay=0.1))。
    • 設置 User-Agent: 使用真實瀏覽器的 User-Agent 字符串。
    • Headless 模式與可視化: 在開發階段,通常建議非無頭模式 (即看得到瀏覽器界面) 方便調試。部署時可考慮無頭模式 (options.add_argument("--headless"))。
  4. DeepSeek API 使用限制與成本: DeepSeek API 有每分鐘請求數 (RPM) 和每分鐘令牌數 (TPM) 的速率限制,同時也會產生調用費用。在設計腳本時,應考慮 API 調用的頻率與必要性。
  5. 安全性考量: 您的 DeepSeek API Key 應被視為敏感信息。
    • 環境變量: 始終建議將 API Key 儲存在環境變量中,而不是直接寫在代碼裡。
    • 避免共享: 不要將包含 API Key 的腳本或配置文件共享給未經授權的人。
  6. 驗證碼處理: 如果登入流程涉及圖片驗證碼,DeepSeek 的文本模型無法直接處理圖片。您可能需要整合專門的驗證碼識別服務(如 2Captcha 或 Anti-Captcha),或者如果驗證碼是簡單的算術或文本題,DeepSeek 可以協助解析文本並生成答案。對於本教程,我們假設沒有複雜的圖形驗證碼。
  7. 腳本維護: 網站的 HTML 結構可能隨時更改,導致 Selenium 的元素定位器失效。定期檢查和更新您的腳本是必要的。

透過將 DeepSeek 的智能決策能力與 Selenium 的精確控制相結合,我們能夠開發出不僅能處理多標籤操作,還能應對動態、複雜登入情境的自動化腳本。這不僅提高了自動化的廣度,也賦予了腳本更強的適應性。