无法初始化Selenium ChromeDriver

yyyllmsg  于 2023-03-10  发布在  Go
关注(0)|答案(1)|浏览(160)

我使用的是最新的Chrome版本110.0.5481.178和最新的Chrome驱动程序110.0.5481.7700
初始化chromedriver var driver = new ChromeDriver(options);时,我收到超时异常。The HTTP request to the remote WebDriver server for URL http://localhost:58801/session timed out after 60 seconds.
直到最新的chrome版本,我的项目都按预期工作,但这个例外突然不断弹出。
我已经下载了相同版本的chrome,但这次是从chromium下载的,作为同一台机器上的独立版本,目标是chrome从“Standalone”目录运行,它工作了!有人能解释这个行为吗?我可以\应该做什么来修复这个问题?

mv1qrgav

mv1qrgav1#

为了继续处理随机异常(偶尔会发生),我像这样启动chromedriver

private IWebDriver StartBrowserChromeHeadless()
{
   var maxRetries = 3;
   var retries = 0;

   while(true)
   {
      try
      {
         return StartBrowserChromeHeadlessDriver();
      }
      catch
      {
         if (retries++ == maxRetries)
         {
            throw;
         }
         Thread.Sleep(5000);
      }
   }
}

private IWebDriver StartBrowserChromeHeadlessDriver()
{
    var chromeOptions = new ChromeOptions();
    chromeOptions.AddArgument("--headless=new");
    chromeOptions.AddArgument("--window-size=1920,1080");
    chromeOptions.AddUserProfilePreference("download.default_directory", downloadFolder);

    var chromeDownload = new Dictionary<string, object>
    {
        { "behavior", "allow" },
        { "downloadPath", downloadFolder }
    };

    var driver = new ChromeDriver(driverFolder, chromeOptions, TimeSpan.FromSeconds(timeoutSecs));
    driver.ExecuteCdpCommand("Browser.setDownloadBehavior", chromeDownload);
    return driver;
}

相关问题