GucciProgrammer
GucciProgrammer

Reputation: 191

Selenium webdriver c# waiting for text to appear

I wish to achieve the

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id='timeLeft']"), "Time left: 7 seconds"));

function in c#, to wait for a text to appear. However, the textToBePresentInElementLocated() is only available in java. Is there a simple way to achieve this in c# , waiting for text to appear on page?

Upvotes: 1

Views: 11076

Answers (4)

Gino Mortillero
Gino Mortillero

Reputation: 123

I was able to resolve this issue by:

element = driver.FindElement(By.Xpath("//div[@id='timeLeft']")));
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.TextToBePresentInElement(name, "Time left: 7 seconds"));

Upvotes: 5

Madhu
Madhu

Reputation: 497

To wait for Text to appear

  do
  {
    Thread.Sleep(2000);
  }

  while(!driver.FindElement(ByXpath("//The Xpath of the TEXT//")).Displayed);

  {

  }

Upvotes: -3

Nikola Josifovic
Nikola Josifovic

Reputation: 21

I have Java version of my method for waiting text to be present in element. Maybe it will help you.

public void waitForText(WebDriver driver, String text, By selector) {
    try {
        WebDriverWait waitElem = new WebDriverWait(driver, WAIT_TIME);
        waitElem.until(ExpectedConditions.textToBePresentInElementLocated(selector, text));
    }catch (TimeoutException e){
        logger.error(e.toString());
    }
}

Method takes instance of webdriver, String to mach text and Element declared in By Class format. WAIT_TIME is constant for wait time in seconds.

Upvotes: 0

Arran
Arran

Reputation: 25076

Selenium is open source, so take a look at what it does:

https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java#L305

You have the power of LINQ however, so it's going to be a little simpler, pseudo:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.IgnoreExceptionTypes(typeof(StaleReferenceException)); // ignore stale exception issues
wait.Until(d => d.FindElement(By.XPath("//div[@id='timeLeft']")).Text.Contains("Time left: 7 seconds"));

The last line will wait until the text returned from d.FindElement(By.XPath("//div[@id='timeLeft']")).Text contains Time left: 7 seconds.

Upvotes: 1

Related Questions