找不到元素时如何avoid/ignore OpenQA.Selenium.NoSuchElementException?
How to avoid/ignore OpenQA.Selenium.NoSuchElementException when element is not found?
我想确定给定的元素不在 DOM 中,或者如果它存在于 DOM 中则不再显示。
为此,我将 WebDriverWait
配置为忽略 NoSuchElementException
和:
public static void WaitForElementToDisappear(IWebDriver driver)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.IgnoreExceptionTypes(typeof(OpenQA.Selenium.NoSuchElementException));
wait.Until(d => d.FindElement(By.ClassName("ClassName")).Displayed == false);
}
不幸的是,exceotion 没有被忽略,测试在它被抛出的那一刻就失败了。
如何处理?
编辑:不幸的是,我发现这是一个理想的等待行为,它在超时之前不会抛出异常,所以我的方式是绝对错误的。
为什么不使用已经存在的 ExpectedConditions
?
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("ClassName")));
None 现有元素被认为是不可见的,您可以在 source code 中看到它,请注意 catch (NoSuchElementException)
块中的注释
public static Func<IWebDriver, bool> InvisibilityOfElementLocated(By locator)
{
return (driver) =>
{
try
{
var element = driver.FindElement(locator);
return !element.Displayed;
}
catch (NoSuchElementException)
{
// Returns true because the element is not present in DOM. The
// try block checks if the element is present but is invisible.
return true;
}
catch (StaleElementReferenceException)
{
// Returns true because stale element reference implies that element
// is no longer visible.
return true;
}
};
}
中也提到了
An expectation for checking that an element is either invisible or not
present on the DOM.
我想确定给定的元素不在 DOM 中,或者如果它存在于 DOM 中则不再显示。
为此,我将 WebDriverWait
配置为忽略 NoSuchElementException
和:
public static void WaitForElementToDisappear(IWebDriver driver)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.IgnoreExceptionTypes(typeof(OpenQA.Selenium.NoSuchElementException));
wait.Until(d => d.FindElement(By.ClassName("ClassName")).Displayed == false);
}
不幸的是,exceotion 没有被忽略,测试在它被抛出的那一刻就失败了。
如何处理?
编辑:不幸的是,我发现这是一个理想的等待行为,它在超时之前不会抛出异常,所以我的方式是绝对错误的。
为什么不使用已经存在的 ExpectedConditions
?
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("ClassName")));
None 现有元素被认为是不可见的,您可以在 source code 中看到它,请注意 catch (NoSuchElementException)
块中的注释
public static Func<IWebDriver, bool> InvisibilityOfElementLocated(By locator)
{
return (driver) =>
{
try
{
var element = driver.FindElement(locator);
return !element.Displayed;
}
catch (NoSuchElementException)
{
// Returns true because the element is not present in DOM. The
// try block checks if the element is present but is invisible.
return true;
}
catch (StaleElementReferenceException)
{
// Returns true because stale element reference implies that element
// is no longer visible.
return true;
}
};
}
中也提到了
An expectation for checking that an element is either invisible or not present on the DOM.