Eli*_*nja 8 c# selenium selenium-webdriver
我正在编写一个测试,我想验证页面上不存在某个元素(显示或以其他方式)。我读过各种文章(例如这篇文章)如何使用空列表或非空列表进行元素检测。这对于验证元素是否存在的相反测试来说效果很好。但是,当该元素不存在时,我在旋转 60 秒后始终会收到 WebDriverException 超时:请参阅此处的屏幕截图
元素检测函数如下:
public bool isButtonPresent(string buttonType)
{
switch (buttonType)
{
case "Button 1":
return !(Driver.FindElements(By.Id("Button 1 ID Here")).Count == 0);
case "Button 2":
return !(Driver.FindElements(By.Id("Button 2 ID Here")).Count == 0);
case "Button 3":
return !(Driver.FindElements(By.Id("Button 3 ID Here")).Count == 0);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
感谢您的时间!
以下是选项:
选项 1:
// Specify the amount of time the driver should wait when searching for an element if it is not immediately present. Specify this time to 0 to move ahead if element is not found.
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
// InvisibilityOfElementLocated will check that an element is either invisible or not present on the DOM.
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(byLocator));
Run Code Online (Sandbox Code Playgroud)
使用这种方法,如果您的下一步操作是单击任何元素,有时您会在 Chrome 浏览器中收到错误 (org.openqa.selenium.WebDriverException: Element is not clickable at point (411, 675))。它在 Firefox 中运行良好。
选项2:
// Set the implicit timeout to 0 as we did in option 1
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
WebDriverWait wait = new WebDriverWait(Driver.Browser, new TimeSpan(0, 0, 15));
try
{
wait.Until(FindElement(By));
}
catch(WebDriverException ex) // Catch the WebDriverException here
{
return;
}
Run Code Online (Sandbox Code Playgroud)
这里我们隐式等待 0 并查找元素。如果元素不存在,它将尝试接下来的 15 秒(您可以根据需要更改此数字)。如果超时,则完成该功能。
选项 3:
Sudeepthi 已经建议过了。
Drivers._driverInstance.FindElement(by).Displayed;
Run Code Online (Sandbox Code Playgroud)