You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Selenium中实现URL重连与登录重试机制?

SiteMinder跳转失败的Selenium登录重试方案

针对SiteMinder偶尔无法跳转至UAT应用导致后续测试全挂的问题,可通过带验证的循环重试机制解决:点击登录后校验跳转结果,失败则重置会话、重新执行登录流程,直到成功或达到重试上限。

核心实现思路

  1. 定义跳转成功的校验规则(URL匹配或标志性元素检测)
  2. 封装带重试逻辑的登录函数,设置最大重试次数
  3. 在test_004中调用该函数,确保跳转成功后再执行后续测试

具体代码示例

from selenium import webdriver
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

def login_with_retry(driver, login_url, uat_target_identifier, max_retries=3):
    retry_count = 0
    while retry_count < max_retries:
        try:
            # 打开SiteMinder登录页
            driver.get(login_url)
            
            # 执行登录操作(替换为你的实际登录元素定位和输入逻辑)
            driver.find_element(By.ID, "username_input").send_keys("your_uat_username")
            driver.find_element(By.ID, "password_input").send_keys("your_uat_password")
            driver.find_element(By.CSS_SELECTOR, "button#login_submit").click()
            
            # 校验是否成功跳转至UAT应用(二选一即可)
            # 方式1:校验URL包含UAT目标路径
            WebDriverWait(driver, 12).until(
                EC.url_contains(uat_target_identifier)
            )
            # 方式2:校验UAT首页标志性元素存在
            # WebDriverWait(driver, 12).until(
            #     EC.visibility_of_element_located((By.ID, "uat_dashboard_logo"))
            # )
            
            print("登录并跳转UAT应用成功")
            return True
            
        except Exception as e:
            retry_count += 1
            print(f"重试登录(第{retry_count}次):{str(e)}")
            # 重置浏览器状态,避免缓存影响
            driver.delete_all_cookies()
            driver.execute_script("window.localStorage.clear();")
            time.sleep(2)  # 增加间隔,降低重试频率
    
    print(f"已达最大重试次数({max_retries}),登录跳转失败")
    return False

# 在test_004中调用重试登录函数
def test_004():
    driver = webdriver.Chrome()
    try:
        # 调用重试登录,传入登录URL和UAT校验标识
        login_success = login_with_retry(
            driver,
            login_url="https://your-siteminder-login.com",
            uat_target_identifier="https://your-uat-app.com/dashboard"
        )
        
        if not login_success:
            # 跳转失败时终止测试,避免后续用例无意义执行
            assert False, "SiteMinder跳转UAT失败,终止测试"
        
        # 此处编写test_004的后续测试逻辑
        # ...
        
    finally:
        driver.quit()

优化建议

  • 调整等待超时:根据SiteMinder实际跳转速度,修改WebDriverWait的超时时间(比如12秒)
  • 日志替代print:使用Python内置logging模块记录重试细节,便于问题排查
  • 指数退避重试:将固定间隔改为指数增长(如2s→4s→8s),减少服务器压力
  • 失败兜底:若多次重试失败,直接标记测试失败并终止,避免后续用例连锁失败

内容的提问来源于stack exchange,提问作者Ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 12:03:16