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

求助:Selenium C#连接Docker Chrome容器新建会话超时问题

问题:Bitbucket Pipelines中standalone-chrome容器自动化测试随机出现会话超时错误

我通过Bitbucket Pipelines在standalone-chrome Docker容器中执行自动化测试,此前数月运行正常,但本周部分测试随机抛出如下错误:

System.InvalidOperationException : Could not start a new session. New session request timed out
Build info: version: '4.3.0', revision: 'a4995e2c09*'
System info: host: '288d627651eb', ip: '172.17.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '5.13.0-1031-aws', java.version: '11.0.15'
Driver info: driver.version: unknown (SessionNotCreated)
   at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.WebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.WebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.WebDriver..ctor(ICommandExecutor executor, ICapabilities capabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
   at AutoTests.Resources.WebdriverFactory.Create() in /opt/atlassian/pipelines/agent/build/AutoTests/Resources/WebdriverFactory.cs:line 78
   at AutoTests.Pages.Outlook.OutlookPage.OpenOutlook() in /opt/atlassian/pipelines/agent/build/AutoTests/Pages/Outlook/OutlookPage.cs:line 64
   at AutoTests.Pages.Outlook.OutlookPage.LoginToOutlook(String emailId, String password) in /opt/atlassian/pipelines/agent/build/AutoTests/Pages/Outlook/OutlookPage.cs:line 30
   at AutoTests.Tests.DualVerificationTests.TC_03_Validate_Self_Registration__Approved() in /opt/atlassian/pipelines/agent/build/AutoTests/Tests/DualVerificationTests.cs:line 292

我了解到该问题可能与shm导致页面崩溃有关,已添加Chrome选项--disable-dev-shm-usage,但问题仍未解决。当前使用的Chrome选项如下:

var chromeDockerOptions = new ChromeOptions();
chromeDockerOptions.AddUserProfilePreference("download.default_directory", GenericHelpers.GetAssemblyLocation());
chromeDockerOptions.AddArgument("--no-sandbox");
chromeDockerOptions.AddArgument("--disable-dev-shm-usage");
chromeDockerOptions.AddUserProfilePreference("profile.default_content_setting_values.automatic_downloads", 1);

return new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), chromeDockerOptions.ToCapabilities(), TimeSpan.FromMinutes(timeout));

解决方案建议

  • 锁定standalone-chrome镜像版本:近期Chrome镜像更新可能引入兼容性问题,避免使用latest标签,指定之前运行稳定的具体版本(如selenium/standalone-chrome:114.0),确保环境一致性。
  • 延长会话超时时间:当前设置的timeout可能不足以应对容器内Chrome启动延迟,尝试将超时时间调整为3-5分钟,给浏览器足够的初始化时间。
  • 添加额外的Chrome启动参数:补充以下参数减少启动负载:
    • --disable-gpu:Docker环境无GPU支持,禁用后可减少初始化开销
    • --start-maximized:避免窗口尺寸适配相关的延迟
    • --disable-extensions:禁用不必要的浏览器扩展,加快启动速度
    • --disable-plugins:减少插件加载带来的资源消耗
  • 提升Pipelines资源配额:在bitbucket-pipelines.yml中增加容器的CPU和内存分配,避免资源不足导致Chrome启动超时:
    options:
      docker:
        memory: 4096
        cpu: 2
    
  • 检查Selenium版本兼容性:确认Selenium 4.3.0与当前使用的Chrome版本匹配,若Chrome镜像已更新,同步升级Selenium到对应兼容版本。
  • 添加会话创建重试机制:在WebdriverFactory.Create()方法中增加重试逻辑,当首次会话创建超时后,重试1-2次,避免偶发超时导致测试失败:
    public IWebDriver Create()
    {
        int retryCount = 2;
        while(retryCount-- > 0)
        {
            try
            {
                var chromeDockerOptions = new ChromeOptions();
                // 保留现有配置
                chromeDockerOptions.AddUserProfilePreference("download.default_directory", GenericHelpers.GetAssemblyLocation());
                chromeDockerOptions.AddArgument("--no-sandbox");
                chromeDockerOptions.AddArgument("--disable-dev-shm-usage");
                chromeDockerOptions.AddUserProfilePreference("profile.default_content_setting_values.automatic_downloads", 1);
                // 新增优化参数
                chromeDockerOptions.AddArgument("--disable-gpu");
                chromeDockerOptions.AddArgument("--start-maximized");
                chromeDockerOptions.AddArgument("--disable-extensions");
                
                return new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), chromeDockerOptions.ToCapabilities(), TimeSpan.FromMinutes(5));
            }
            catch (SessionNotCreatedException)
            {
                if(retryCount == 0) throw;
                Thread.Sleep(2000);
            }
        }
        throw new InvalidOperationException("Failed to create webdriver after retries");
    }
    
  • 复用浏览器会话:如果测试场景允许,尝试在多个测试用例间复用同一个浏览器会话,减少频繁创建新会话的开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:48:18