Selenium C# locators and WebDriverWait
On this page
Almost every line of a Selenium test either finds an element or waits for one. This chapter covers both, because they fail together: most "element not found" errors are timing problems, not locator problems.
The By strategies#
driver.FindElement(By...) returns the first matching IWebElement or throws NoSuchElementException. Create LocatorTests.cs:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace SeleniumCourse;
public class LocatorTests
{
private const string WebForm = "https://www.selenium.dev/selenium/web/web-form.html";
private IWebDriver driver = null!;
[SetUp]
public void StartBrowser()
{
driver = new ChromeDriver();
driver.Navigate().GoToUrl(WebForm);
}
[TearDown]
public void StopBrowser() => driver.Quit();
[Test]
public void FindsElementsWithEachStrategy()
{
IWebElement text = driver.FindElement(By.Id("my-text-id"));
IWebElement password = driver.FindElement(By.Name("my-password"));
IWebElement textarea = driver.FindElement(By.CssSelector("textarea[name='my-textarea']"));
IWebElement submit = driver.FindElement(By.XPath("//button[text()='Submit']"));
IWebElement heading = driver.FindElement(By.TagName("h1"));
IWebElement link = driver.FindElement(By.LinkText("Return to index"));
Assert.That(text.GetDomAttribute("myprop"), Is.EqualTo("myvalue"));
Assert.That(password.GetDomAttribute("type"), Is.EqualTo("password"));
Assert.That(textarea.TagName, Is.EqualTo("textarea"));
Assert.That(submit.Enabled, Is.True);
Assert.That(heading.Text, Is.EqualTo("Web form"));
Assert.That(link.GetDomAttribute("href"), Is.EqualTo("./index.html"));
}
}
| Strategy | Example | Use it when |
|---|---|---|
By.Id |
By.Id("my-text-id") |
the element has a stable, unique id: the first choice |
By.Name |
By.Name("my-password") |
form fields, whose name is part of the form's contract with the server |
By.CssSelector |
By.CssSelector("[data-test='save']") |
anything else; a data-test attribute added for tests is the most stable option |
By.XPath |
By.XPath("//button[text()='Submit']") |
you must match on text or walk up the tree, which CSS cannot do |
By.LinkText |
By.LinkText("Return to index") |
links, by their exact visible text |
By.TagName, By.ClassName
|
By.ClassName("redbox") |
there is exactly one, or you want all of them |
Prefer locators that describe what an element is (its id, name, a test attribute) over where it sits. By.XPath("/html/body/main/div[2]/form/div/div[1]/label[1]/input") breaks the moment a designer wraps the form in one more div.
Two attribute methods show up in the test. GetDomAttribute("href") returns the attribute as written in the HTML (./index.html). GetDomProperty("value") returns the live JavaScript property, which is what you want for the current contents of an input after the user types. The older GetAttribute still exists but returns one or the other depending on the attribute, so prefer the two explicit methods.
Many elements, or none#
FindElements (plural) returns all matches, and an empty list rather than an exception when nothing matches:
[Test]
public void FindElementsReturnsAllMatches()
{
IReadOnlyCollection<IWebElement> checkboxes =
driver.FindElements(By.CssSelector("input[type='checkbox']"));
Assert.That(checkboxes, Has.Count.EqualTo(2));
Assert.That(checkboxes.Count(c => c.Selected), Is.EqualTo(1));
}
[Test]
public void FindElementsReturnsEmptyWhenNothingMatches()
{
Assert.That(driver.FindElements(By.Id("no-such-id")), Is.Empty);
Assert.Throws<NoSuchElementException>(() => driver.FindElement(By.Id("no-such-id")));
}
That makes FindElements(...).Count == 0 the idiomatic way to check that something is absent.
Dropdowns#
A native <select> is easiest through SelectElement from Selenium.Support:
[Test]
public void SelectsFromADropdown()
{
var select = new SelectElement(driver.FindElement(By.Name("my-select")));
select.SelectByText("Two");
Assert.That(select.SelectedOption.GetDomAttribute("value"), Is.EqualTo("2"));
}
It also has SelectByValue and SelectByIndex. It only works on real <select> elements; a dropdown built from divs is clicked like any other element.
You need to assert that an error banner is not on the page. Which check is right?
FindElements returns an empty collection when nothing matches, which is exactly the assertion. FindElement never returns null; it throws, so option b errors instead of passing, and catching the exception hides other failures too.
Waits: the failure#
The practice page dynamic.html has an "Add a box!" button that appends a red box, #box0, one second after the click. Create WaitTests.cs with the same SetUp and TearDown as above, opening https://www.selenium.dev/selenium/web/dynamic.html, and this test:
[Test]
public void WithoutAWait()
{
driver.FindElement(By.Id("adder")).Click();
driver.FindElement(By.Id("box0")); // NoSuchElementException
}
Failed WithoutAWait [1 s]
OpenQA.Selenium.NoSuchElementException : no such element: Unable to locate element: {"method":"css selector","selector":"#box0"}
The locator is right. The element just does not exist yet: FindElement looks once and gives up.
Thread.Sleep(2000) before the lookup makes it pass, and costs two seconds on every run whether the box takes 1 second or 0.1, and fails again the day CI is slower than your guess. A large implicit wait (driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10)) retries every lookup, but only checks that an element is present, not visible or enabled, makes every check for an absent element take the full ten seconds, and combines unpredictably with explicit waits. Leave the implicit wait at its default of zero.
WebDriverWait with a lambda#
An explicit wait polls a condition until it succeeds or a timeout expires:
[Test]
public void WithAnExplicitWait()
{
driver.FindElement(By.Id("adder")).Click();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IWebElement box = wait.Until(d => d.FindElement(By.Id("box0")));
Assert.That(box.GetDomAttribute("class"), Is.EqualTo("redbox"));
}
Until calls the lambda every 500 milliseconds (the default polling interval). It returns as soon as the lambda returns something that is neither null nor false, here the element, and throws WebDriverTimeoutException when the timeout runs out. WebDriverWait ignores NoSuchElementException while it polls, which is why calling FindElement inside the lambda is fine. This test ran in about 2 seconds against Thread.Sleep's 3 in the same setup: the wait continues the moment the box exists.
In Selenium 4.52 WebDriverWait is part of the Selenium.WebDriver package itself, in the OpenQA.Selenium.Support.UI namespace.
Where is ExpectedConditions?#
Older C# tutorials write wait.Until(ExpectedConditions.ElementIsVisible(By.Id("x"))). In current Selenium .NET that does not compile:
error CS0103: The name 'ExpectedConditions' does not exist in the current context
The class was deprecated in the .NET bindings in Selenium 3.11 and is not part of Selenium 4. A community copy lives on as the DotNetSeleniumExtras.WaitHelpers NuGet package, but its last release is 3.11.0 from March 2018. You do not need it: a lambda says the same thing, is checked by the compiler, and can express conditions no helper class anticipated.
| Wait for | Lambda |
|---|---|
| present in the DOM | d => d.FindElement(locator) |
| visible | d => d.FindElement(locator).Displayed |
| visible, returning the element | d => { var e = d.FindElement(locator); return e.Displayed ? e : null; } |
| clickable | d => { var e = d.FindElement(locator); return e.Displayed && e.Enabled ? e : null; } |
| text appears | d => d.FindElement(locator).Text.Contains("Saved") |
| gone | d => d.FindElements(locator).Count == 0 |
| URL or title |
d => d.Url.Contains("/done"), d => d.Title == "Web form - target page"
|
The page also has a hidden input that a second button reveals after a second. It is in the DOM from the start, so waiting for presence returns at once and typing fails with ElementNotInteractableException. Wait for visibility instead:
[Test]
public void WaitsForVisibility()
{
IWebElement revealed = driver.FindElement(By.Id("revealed"));
driver.FindElement(By.Id("reveal")).Click();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(_ => revealed.Displayed);
revealed.SendKeys("now visible");
Assert.That(revealed.GetDomProperty("value"), Is.EqualTo("now visible"));
}
You paste wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("save"))) from an old answer and get CS0103. What do you write instead?
Current Selenium .NET has no ExpectedConditions; Until takes any lambda and keeps polling while it returns null or false. Downgrading to Selenium 3 loses W3C support and Selenium Manager, and a sleep is a guess.
Conditions of your own#
A lambda can wait for anything you can compute. Click "Add a box!" three times and wait for all three:
[Test]
public void WaitsForACount()
{
IWebElement adder = driver.FindElement(By.Id("adder"));
for (int i = 0; i < 3; i++)
{
adder.Click();
}
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
var boxes = wait.Until(d =>
{
var found = d.FindElements(By.ClassName("redbox"));
return found.Count == 3 ? found : null; // null means "keep polling"
});
Assert.That(boxes, Has.Count.EqualTo(3));
}
Set Message so a timeout says what was missing instead of only how long it waited:
[Test]
public void TimesOutWithAMessage()
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2))
{
Message = "#revealed never became visible"
};
var error = Assert.Throws<WebDriverTimeoutException>(
() => wait.Until(d => d.FindElement(By.Id("revealed")).Displayed));
Assert.That(error.Message, Does.Contain("#revealed never became visible"));
}
Two more settings are useful: wait.PollingInterval changes the 500 ms default, and wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)) keeps polling when the page re-renders the element you are checking.
The rules: wait for the condition the next line depends on, never for a duration; keep the implicit wait at zero; and do not "fix" an intermittent failure by raising a timeout before you know which condition was not yet true. The flaky tests course covers the other common causes.
Every test class so far starts its own browser in its own SetUp. The next chapter moves that into one place.