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

使用Python和Selenium实现连接超时后从头循环直至成功

Fixing Your Selenium Retry Loop for Connection Timeouts

Got it, let's get your script working so it retries from the start every time there's a connection timeout or failure until it succeeds. Your current logic has a few key issues that we'll fix step by step.

What's Wrong With the Original Code?

  • The finally block runs no matter if your try code succeeds or fails. That means even after you successfully enter the name and click "verify", it'll still click the "try again" button—completely undoing your success.
  • You aren't catching timeout or element-not-found exceptions, so the script can't tell when a connection failure happens to trigger a retry.
  • The browser instance is created outside the loop, so if the page times out, it stays stuck on the error page instead of starting fresh.

Corrected Code

Here's a revised version that handles retries properly, starting over from scratch every time there's a failure:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time

def run_until_success():
    # 无限循环,直到操作成功
    while True:
        browser = None
        try:
            # 每次重试都重新初始化浏览器,避免残留错误状态
            browser = webdriver.Chrome('C:/Users/acer/Desktop/chromedriver')
            # 打开目标网站
            browser.get('website')
            time.sleep(1)  # 简单等待页面加载(建议后续换成显式等待更可靠)
            
            # 执行核心操作:输入名称 + 点击验证
            browser.find_element_by_id('q').send_keys('name')
            verify_button = browser.find_element_by_tag_name('button')
            verify_button.click()
            
            # 可选:添加成功验证步骤(比如检查是否出现成功提示)
            # browser.find_element_by_id('success_indicator')  # 替换成实际的成功元素ID
            
            print("操作成功!")
            break  # 成功后跳出无限循环
        
        # 捕获常见的连接/页面加载异常
        except (TimeoutException, NoSuchElementException) as e:
            print(f"遇到超时或元素找不到错误,正在重试:{str(e)}")
            # 关闭当前浏览器,避免资源占用
            if browser:
                browser.quit()
            # 重试前等待3秒,防止频繁请求被网站拦截
            time.sleep(3)
        
        # 捕获其他未知异常,同样重试
        except Exception as e:
            print(f"发生未知错误,正在重试:{str(e)}")
            if browser:
                browser.quit()
            time.sleep(3)

# 启动脚本
run_until_success()

Key Improvements Explained

  • Full loop reset: Every retry creates a fresh browser instance and reloads the page, so you're always starting from a clean state.
  • Targeted exception handling: We catch TimeoutException (for connection timeouts) and NoSuchElementException (for when elements don't load due to failure), which are the most common issues here.
  • Success exit: Once the operations complete successfully, the break statement exits the infinite loop.
  • Resource cleanup: We close the browser on failure to avoid leaving unused Chrome instances running in the background.
  • Rate limiting: The 3-second wait between retries prevents your script from spamming the website, which could get you blocked.

Bonus Tip

Replace the time.sleep(1) with explicit waits (using WebDriverWait) for more reliability. Explicit waits wait until elements are actually loaded instead of just waiting a fixed time. For example:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待输入框加载完成,最多等10秒
WebDriverWait(browser, 10).until(
    EC.presence_of_element_located(('id', 'q'))
).send_keys('name')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:12:43