'How to wait for a WebElement to have a specific text value (Selenium C#)
I know I can wait for an element to exist by doing this:
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
var element = wait.Until(d => d.FindElement(By.Id("foo-status")));
If it doesn't exist within 5 seconds, element is null.
How do I get Selenium to wait for the element to have a certain text value?
(I have answered my own question, but would be keen for any better answers or improvements.)
Solution 1:[1]
The trick is to use a filter method that returns null if the text does not match.
public static IWebElement ElementTextFilter(IWebElement webElement, string text) {
if (webElement == null)
return null;
return webElement.Text.Equals(text, StringComparison.OrdinalIgnoreCase)
? webElement : null;
}
// ...
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
var expectedText = "good";
var element = wait.Until(d =>
ElementTextFilter(d.FindElement(By.Id("foo-status")), expectedText)
);
Can easily turn this into an extension method which is a bit cleaner.
public static class WebElementExtensions {
public static IWebElement WithText(this IWebElement webElement, string text) {
if (webElement == null)
return null;
return webElement.Text.Equals(text, StringComparison.OrdinalIgnoreCase)
? webElement : null;
}
// ...
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
var expectedText = "good";
var element = wait.Until(d => d.FindElement(By.Id("foo-status")).WithText(expectedText));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
