C# and Selenium: Wait Until Element is Present


We can wait until an element is present in Selenium webdriver using the explicit wait. It is mainly used whenever there is a synchronization issue for an element to be available on page.

The WebDriverWait and the ExpectedCondition classes are used for an explicit wait implementation. We have to create an object of the WebDriverWait which shall invoke the methods of the ExpectedCondition class.

The webdriver waits for a specified amount of time for the expected criteria to be met. After the time has elapsed, an exception gets thrown. To wait for an element to be present, we have to use the expected condition – ElementExists.

Syntax

WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
w.Until(ExpectedConditions.ElementExists(By.TagName("h1")));

Let us try to wait for the text - About Careers at Tutorials Point to be available on the page −

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace NUnitTestProject2{
   public class Tests{
      String url ="https://www.tutorialspoint.com/about/about_careers.htm";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         driver = new FirefoxDriver("");
      }
      [Test]
      public void Test2(){
         //URL launch
         driver.Navigate().GoToUrl(url);
         //identify element then click
         IWebElement l = driver.FindElement(By.XPath("//*[text()='Careers']"));
         l.Click();
         //expected condition of ElementExists
         WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
         w.Until(ExpectedConditions.ElementExists(By.TagName("h1")));
         //identify element then obtain text
         IWebElement m = driver.FindElement(By.TagName("h1"));
         Console.WriteLine("Element text is: " + m.Text);
      }
      [TearDown]
      public void close_Browser(){
         driver.Quit();
      }
   }
}

Output

Updated on: 07-Apr-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements