Skip to content

Instantly share code, notes, and snippets.

@Sugrob57
Last active March 5, 2020 11:19
Show Gist options
  • Save Sugrob57/54f67670a940493d50f7139a6800ee97 to your computer and use it in GitHub Desktop.
Save Sugrob57/54f67670a940493d50f7139a6800ee97 to your computer and use it in GitHub Desktop.
Wait element displayed sample
var myElement = WaitUntilElementIsDisplayed(By.XPath(myElementXpath));
// дождаться пока элемент появится
public IWebElement WaitUntilElementIsDisplayed(By locator, TimeSpan? timeout = null)
{
timeout = timeout ?? ElementWaitingTimeout;
return WaitForElement(
() =>
{
var element = new WebDriverWait(WebDriver, timeout.Value)
.Until(driver => driver.FindElement(locator));
new WebDriverWait(WebDriver, timeout.Value)
.Until(driver => element.Displayed);
return element;
},
locator);
}
// дождаться пока элемент появится и будет доступен для клика
public IWebElement WaitUntilElementIsClickable(By locator, TimeSpan? timeout = null)
{
timeout = timeout ?? ElementWaitingTimeout;
return WaitForElement(
() =>
{
var element = new WebDriverWait(WebDriver, timeout.Value)
.Until(driver => driver.FindElement(locator));
new WebDriverWait(WebDriver, timeout.Value)
.Until(driver => element.Enabled && element.Displayed);
return element;
},
locator);
}
private IWebElement WaitForElement(Func<IWebElement> action, By locator)
{
IWebElement element = null;
var staleElement = true;
while (staleElement)
{
try
{
element = action();
staleElement = false;
}
catch (StaleElementReferenceException)
{
Log.Error("StaleElementReferenceException occurred while waiting for element by {by}: {exception}.", locator);
staleElement = true;
}
catch (Exception ex)
{
Log.Error("Exception occurred while waiting for element by {by}: {exception}.", locator, ex.Message);
return null;
}
}
return element;
}
private static readonly TimeSpan ElementWaitingTimeout = TimeSpan.FromSeconds(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment