在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) { }
,但仍然没有发现错误。
带有错误的图像
不使用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的帮助。