【问题标题】:C# Selenium: Can't catch exception when using wait.UntilC# Selenium:使用 wait.Until 时无法捕获异常
【发布时间】:2022-01-21 14:01:42
【问题描述】:

在 try / catch 块中使用 wait.Until() 时,如果元素不存在,则会引发 NoSuchElementException 异常。但是,当我尝试捕获异常时,仍然会收到错误消息。

        try
        {
            wait.Until(el => el.FindElement(By.Id("courseTestItem")));
            driver.Close();
            driver.SwitchTo().Window(driver.WindowHandles.Last());
            Console.WriteLine("Skipped: " + courses[0].Item1.Text + " (Has test)");
        }
        catch (OpenQA.Selenium.NoSuchElementException) { }

我什至尝试只使用catch (Exception e) { },但仍然没有发现错误。

Image with the error

【问题讨论】:

    标签: c# selenium try-catch


    【解决方案1】:

    而不是使用 try / catch 使用:

    if (wait.Until(el => el.FindElements(By.Id("filterText"))).Count > 0) { }
    else if (wait.Until(el => el.FindElements(By.Id("sp-search-results-search"))).Count > 0) { }
    else System.Threading.Thread.Sleep(5000);
    

    这会检查是否找到超过 0 个符合条件的元素,这意味着找到了该元素。

    感谢 Reddit 上 u/Simmo7 的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2016-07-01
      • 1970-01-01
      相关资源
      最近更新 更多