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

Watir脚本偶发Net::ReadTimeout错误,重试仍无效求解决方案

针对Watir脚本偶发Net::ReadTimeout的解决建议

这种偶发的超时问题确实挺头疼的,我给你几个实际可行的调整方案,你可以逐一尝试:

  • 给重试逻辑加次数限制和延迟
    你当前的代码是无限重试,但如果连续几次请求都遇到超时,无限重试意义不大,还可能给服务器造成压力。建议加上重试次数上限和等待延迟:

    attempts = 3
    url = "https://www.google.com/"
    begin
      browser = Watir::Browser.start url
    rescue Net::ReadTimeout
      attempts -= 1
      if attempts > 0
        sleep 2 # 每次重试前等待2秒,给网络和服务器缓冲时间
        retry
      else
        raise "经过3次尝试后仍无法加载#{url},触发超时"
      end
    end
    
  • 调整Chrome的超时参数
    Watir基于Selenium,你可以通过ChromeOptions直接设置页面加载的超时阈值,延长默认的等待时间:

    options = Selenium::WebDriver::Chrome::Options.new
    # 设置页面加载超时为30秒(按需调整)
    options.add_argument('--page-load-timeout=30')
    # 设置脚本超时为30秒
    options.add_argument('--timeout=30000')
    
    browser = Watir::Browser.new :chrome, options: options
    browser.goto(url)
    
  • 改用更宽松的页面加载策略
    默认的页面加载策略会等待所有资源(图片、广告、第三方脚本)加载完成才继续,这很容易触发超时。可以改成eager策略,只要DOM结构加载完成就执行后续逻辑:

    options = Selenium::WebDriver::Chrome::Options.new
    options.add_option('pageLoadStrategy', 'eager')
    
    browser = Watir::Browser.new :chrome, options: options
    browser.goto(url)
    
  • 检查ChromeDriver与Chrome版本兼容性
    版本不匹配是自动化脚本出现奇怪问题的常见原因,一定要确保你的ChromeDriver版本和Chrome浏览器的大版本完全一致(比如Chrome 118对应ChromeDriver 118.x),小版本尽量接近。

  • 模拟真实浏览器的请求头
    部分网站会对自动化工具的请求做限流或拦截,导致超时。你可以添加真实的User-Agent等请求头,让请求更贴近普通用户:

    options = Selenium::WebDriver::Chrome::Options.new
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
    
    browser = Watir::Browser.new :chrome, options: options
    browser.goto(url)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:06:28