如果Selenium Testing中不存在任何元素,那么我无法处理它。我试过这段代码。
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
它显示超时异常花费的时间超过1分钟,最后由主Exception类处理,但我的自动化测试停止了,我不想停止测试。
我也试过这段代码。
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
我该怎么做才能在很短的时间内返回真或假。
答案 0 :(得分:1)
另一种选择是
return driver.FindElements(by).length > 0;
答案 1 :(得分:0)
我通常使用Displayed属性。我在下面的示例中使用了具有预定IWebElements的页面对象模型:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}
答案 2 :(得分:-1)
try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
请尝试让我知道.......