Search code examples
c#seleniumselenium-webdriverwebdriver

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

  • An easier solution for your usecase to wait for the element to have a certain text can be implemented with the help of ExpectedConditions in-conjunction with the method TextToBePresentInElement as follows :

    wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
    var expectedText = "good";
    var element = wait.Until(ExpectedConditions.TextToBePresentInElement(By.Id("foo-status"), expectedText));