tnw tnw - 3 months ago 10
C# Question

NoSuchElementException despite using WebDriverWait

I'm using Selenium to locate an element and populate it with text. When I browse to my URL, a text box shows first which loads the page. Once the app is loaded, a login username/password is shown. I just want to wait until the login username/password is displayed to avoid a NoSuchElementException. I've referenced this post but cannot get any of the solutions there to work.

When I run the test, it does not wait for the element to appear and immediately fails on

x.FindElement(By.Id("UserName")
with a
NoSuchElementException
.

using (IWebDriver driver = new ChromeDriver(@"<my path>"))
{
driver.Manage().Window.Maximize();

driver.Navigate().GoToUrl("<my url>");

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(600));
var userName = wait.Until(x => x.FindElement(By.Id("UserName")));

userName.SendKeys("username");

IWebElement pass = driver.FindElement(By.Id("Password"));
pass.SendKeys("password");
}


What am I doing wrong here? How should I change my code to wait for the
UserName
id to be present before looking for it?

Answer

I think you need to wait first invisibility of loading element then go to wait for visibility of username as below :-

 var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));

wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ID("id of loading element ")));

//Now go to find username element 
var userName = wait.Until(ExpectedConditions.ElementIsVisible(By.ID("UserName")));
userName.SendKeys("username");
Comments