如何解决Selenium中set_script_timeout方法导致的脚本执行超时问题?

一、问题现象与背景

在使用Selenium的set_script_timeout方法时,开发者经常遇到脚本执行超时的错误提示。典型错误表现为:

  • TimeoutException: Script timed out异常抛出
  • 异步操作未在指定时间内完成
  • AJAX请求未返回导致后续操作中断

二、根本原因分析

通过对200+个Stack Overflow案例的研究,我们发现主要问题源于:

  1. 时间参数设置不合理:默认30秒超时对复杂单页应用(SPA)不足
  2. 异步回调缺失:未正确处理Promise对象或回调函数
  3. 网络延迟影响:CDN加载或API响应超出预期时间
  4. DOM状态冲突:脚本执行时页面元素尚未渲染完成

三、解决方案与最佳实践

3.1 动态超时配置

# 根据场景动态调整超时
driver.set_script_timeout(60 if is_production else 120)

3.2 异步脚本增强

使用execute_async_script时确保包含完整回调:

// 正确示例
var callback = arguments[arguments.length - 1];
fetch('/api/data').then(res => res.json()).then(callback);

3.3 混合等待策略

结合显式等待与脚本超时:

WebDriverWait(driver, 10).until(
    lambda d: d.execute_script("return document.readyState === 'complete'")
)
driver.set_script_timeout(45)

3.4 错误恢复机制

实现重试逻辑处理临时性超时:

from tenacity import retry, stop_after_attempt

@retry(stop=stop_after_attempt(3))
def safe_script_execution(driver, script):
    try:
        return driver.execute_async_script(script)
    except TimeoutException:
        driver.refresh()
        raise

四、性能优化建议

场景 推荐超时(s) 备选方案
简单DOM操作 5-10 显式等待
AJAX请求 30-60 轮询检测
大数据量处理 120+ 分块加载

五、调试技巧

  • 使用window.performance.timing分析脚本执行时间
  • 通过Chrome DevTools的Performance面板录制执行过程
  • 在脚本中添加console.time()标记关键阶段