Selenium-等待元素出现,即使在C#中的可滚动模态上也是可见和可交互的



这里对python提出了同样的问题:Selenium-等待元素出现,可见且可交互。然而,答案并没有涵盖所有情况。

当我不处于调试模式时,我的实现会不时失败。我认为等待ID是一项微不足道的任务,应该有一个直接的KISS实现,而且永远不会失败。

public IWebElement WaitForId(string inputId, bool waitToInteract = false, int index = 0)
{
IWebElement uiElement = null;
while (uiElement == null)
{
var items = WebDriver.FindElements(By.Id(inputId));
var iteration = 0;
while (items == null || items.Count < (index + 1) ||
(waitToInteract && (!items[index].Enabled || !items[index].Displayed)))
{
Thread.Sleep(500);
items = WebDriver.FindElements(By.Id(inputId));
if (items.Count == 0 && iteration == 10)
{
// "still waiting...: " + inputId
}
if (iteration == 50)
{
// "WaitForId not found: " + inputId
Debugger.Break(); // if tried too many times, maybe you want to investigate way
}
iteration++;
}
uiElement = WebDriver.FindElement(By.Id(inputId));
}
return uiElement;
}
public IWebElement GetActiveElement(string id, int allowedTimeout = 20, int retryInterval = 250)
{
var wait = new DefaultWait<IWebDriver>(_driver)
{
Timeout = TimeSpan.FromSeconds(allowedTimeout),
PollingInterval = TimeSpan.FromMilliseconds(retryInterval)
};
return wait.Until(d =>
{
var element = d.FindElement(By.Id(id));
return element.Displayed || element.Enabled ? element : throw new NoSuchElementException();
});
// Usage would be something like this
GetActiveElement("foo").SendKeys("Bar");

您应该能够创建扩展方法并调用扩展而不是

public static class WebDriverExtension
{
public static IWebElement GetActiveElement(this IWebDriver driver, string id, int allowedTimeout = 20, int retryInterval = 250)
{
var wait = new DefaultWait<IWebDriver>(driver)
{
Timeout = TimeSpan.FromSeconds(allowedTimeout),
PollingInterval = TimeSpan.FromMilliseconds(retryInterval)
};
return wait.Until(d =>
{
var element = d.FindElement(By.Id(id));
return element.Displayed || element.Enabled ? element : throw new NoSuchElementException();
});
}
}
// usage 
_driver.GetActiveElement("foo").SendKeys("bar");

最新更新