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

Selenium ChromeDriver定义偶尔卡死,如何设置超时与重试机制?

解决ChromeDriver初始化卡住的超时重试方案

针对ChromeDriver初始化偶尔卡住的问题,可以通过超时控制+重试机制自动处理,无需手动重启代码。以下是具体实现思路和代码示例:

核心思路

  1. 超时控制:用线程单独执行Driver初始化操作,设置时间阈值,超过时间则判定为超时并终止操作,抛出异常。
  2. 重试机制:捕获超时或初始化失败的异常,自动重新执行初始化逻辑,直到成功或达到最大重试次数。

代码实现

方式1:自定义线程超时+重试循环

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import threading

# 全局变量存储Driver实例和初始化错误信息
driver_instance = None
init_error = None

def init_driver():
    global driver_instance, init_error
    try:
        service = Service(executable_path=r'/usr/bin/chromedriver')
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-infobars")
        options.add_argument("start-maximized")
        options.add_argument("--disable-extensions")
        # 额外添加避免共享内存不足的参数
        options.add_argument("--disable-dev-shm-usage")
        driver_instance = webdriver.Chrome(service=service, options=options)
    except Exception as e:
        init_error = e

def get_driver_with_timeout(max_wait_time=10, max_retries=3):
    global driver_instance, init_error
    retry_count = 0
    while retry_count < max_retries:
        driver_instance = None
        init_error = None
        # 启动线程执行初始化
        init_thread = threading.Thread(target=init_driver)
        init_thread.start()
        # 等待指定时间,超时则终止线程
        init_thread.join(timeout=max_wait_time)
        
        if init_thread.is_alive():
            print(f"第{retry_count+1}次初始化超时,正在重试...")
            retry_count += 1
            continue
        if init_error:
            print(f"第{retry_count+1}次初始化失败:{init_error}")
            retry_count += 1
            continue
        # 初始化成功,返回Driver实例
        return driver_instance
    
    # 达到最大重试次数仍失败
    raise Exception(f"经过{max_retries}次重试后,Driver初始化仍失败")

# 使用示例
try:
    driver = get_driver_with_timeout(max_wait_time=10, max_retries=3)
    driver.get("https://example.com")
    print(driver.title)
finally:
    if 'driver' in locals():
        driver.quit()

方式2:用concurrent.futures+tenacity简化重试

先安装依赖:pip install tenacity

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from concurrent.futures import ThreadPoolExecutor
from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_type

class DriverInitTimeout(Exception):
    pass

def init_driver():
    service = Service(executable_path=r'/usr/bin/chromedriver')
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-infobars")
    options.add_argument("start-maximized")
    options.add_argument("--disable-extensions")
    options.add_argument("--disable-dev-shm-usage")
    return webdriver.Chrome(service=service, options=options)

def get_driver_with_timeout(max_wait_time=10):
    with ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(init_driver)
        try:
            return future.result(timeout=max_wait_time)
        except TimeoutError:
            raise DriverInitTimeout("Driver初始化超时")

# 配置重试规则:最多3次,每次间隔2秒,仅在超时或初始化异常时重试
@retry(stop=stop_after_attempt(3), wait=wait_fixed(2), retry=retry_if_exception_type((DriverInitTimeout, Exception)))
def get_retry_driver():
    return get_driver_with_timeout(max_wait_time=10)

# 使用示例
try:
    driver = get_retry_driver()
    driver.get("https://example.com")
    print(driver.title)
finally:
    if 'driver' in locals():
        driver.quit()

额外优化建议

  • 确保chromedriver版本与Chrome浏览器版本完全匹配,版本不兼容是初始化卡住的常见原因。
  • 重试前可清理残留Chrome进程(Linux下执行pkill -f chrome),避免旧进程干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:15:03