我得到他的代码等待找到控件
WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
var ok = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]")));
当任何事件发生后在 dom 中进行某些控制时,我会使用它。
现在,如果我缩小页面中的搜索范围[就像在 WebDriver 中获取一个 div,它是一个 WebElement] 那么我如何在该范围内搜索任何控件,直到找到它或发生超时?
最佳答案
您需要设置不同的等待时间,使用 DefaultWait
类:
var waitInnerScope = new DefaultWait<IWebElement>(divInsideWebDriver);
waitInnerScope.Timeout = TimeSpan.FromSeconds(timeout);
waitInnerScope.IgnoreExceptionTypes(typeof(NoSuchElementException));
然后与wait.Until
一起使用:
var ok = waitInnerScope.Until(PresenceOfAllElementsLocatedBy(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]")));
编辑:自ExpectedConditions
由实现 Func<IWebDriver, ...>
的静态方法组成用于 WebDriverWait
, 你必须使用你自己的方法来获取 IWebElement
这样:
public static Func<IWebElement, ReadOnlyCollection<IWebElement>> PresenceOfAllElementsLocatedBy(By locator)
{
return (element) =>
{
try
{
var elements = element.FindElements(locator);
return elements.Any() ? elements : null;
}
catch (StaleElementReferenceException)
{
return null;
}
};
}
或者您可以像这样对匿名方法使用 lambda 表达式:
waitInnerScope.Until<ReadOnlyCollection<IWebElement>>((element) =>
{
try
{
var elements = element.FindElements(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]"));
return elements.Any() ? elements : null;
}
catch (StaleElementReferenceException)
{
return null;
}
});
关于c# - 如何使用运行时发生变化的 WebElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038677/