---
title: Selenium C# locators and WebDriverWait | TestingBot
description: 'Almost every line of a Selenium test either finds an element or waits
  for one. This chapter covers both, because they fail together: most &quot;element
  not…'
source_url:
  html: https://testingbot.com/resources/courses/selenium-csharp/locators-and-waits
  md: https://testingbot.com/resources/courses/selenium-csharp/locators-and-waits.md
---

Course

[Selenium C# Tutorial with NUnit](https://testingbot.com/resources/courses/selenium-csharp)

Chapter 3 of 10

1. [1 Selenium C# Tutorial with NUnit](https://testingbot.com/resources/courses/selenium-csharp)
2. [2 Set up .NET, Selenium and NUnit](https://testingbot.com/resources/courses/selenium-csharp/setup-and-first-test)
3. [3 Selenium C# locators and WebDriverWait](https://testingbot.com/resources/courses/selenium-csharp/locators-and-waits)
4. [4 NUnit fixtures, attributes and [TestCase] ](https://testingbot.com/resources/courses/selenium-csharp/nunit-fixtures-and-attributes)
5. [5 NUnit assertions and screenshots on failure](https://testingbot.com/resources/courses/selenium-csharp/assertions-and-screenshots)
6. [6 Page objects in C#](https://testingbot.com/resources/courses/selenium-csharp/page-objects)
7. [7 Run Selenium C# tests on the TestingBot grid](https://testingbot.com/resources/courses/selenium-csharp/run-on-testingbot)
8. [8 Parallel Selenium tests with NUnit](https://testingbot.com/resources/courses/selenium-csharp/parallel-tests)
9. [9 Selenium C# tests in CI](https://testingbot.com/resources/courses/selenium-csharp/ci-with-github-actions)
10. [10 Selenium C# Quiz](https://testingbot.com/resources/courses/selenium-csharp/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 3 of 10 Intermediate 8 min read 2 quick checks Updated Nov 2026 

# Selenium C# locators and WebDriverWait
On this page
1. [The By strategies](https://testingbot.com#the-by-strategies)
2. [Many elements, or none](https://testingbot.com#many-elements-or-none)
3. [Dropdowns](https://testingbot.com#dropdowns)
4. [Waits: the failure](https://testingbot.com#waits-the-failure)
5. [WebDriverWait with a lambda](https://testingbot.com#webdriverwait-with-a-lambda)
6. [Where is ExpectedConditions?](https://testingbot.com#where-is-expectedconditions)
7. [Conditions of your own](https://testingbot.com#conditions-of-your-own)

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[#](https://testingbot.com#the-by-strategies)

`driver.FindElement(By...)` returns the first matching `IWebElement` or throws `NoSuchElementException`. Create `LocatorTests.cs`:

```csharp
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[#](https://testingbot.com#many-elements-or-none)

`FindElements` (plural) returns all matches, and an **empty list** rather than an exception when nothing matches:

```csharp
[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[#](https://testingbot.com#dropdowns)

A native `<select>` is easiest through `SelectElement` from `Selenium.Support`:

```csharp
[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 `div`s is clicked like any other element.

You need to assert that an error banner is _not_ on the page. Which check is right?

 `Assert.That(driver.FindElements(By.Id("error")), Is.Empty)` `Assert.That(driver.FindElement(By.Id("error")), Is.Null)` Wrap `FindElement` in `try` and pass the test in the `catch`.

`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[#](https://testingbot.com#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:

```csharp
[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[#](https://testingbot.com#webdriverwait-with-a-lambda)

An explicit wait polls a condition until it succeeds or a timeout expires:

```csharp
[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?[#](https://testingbot.com#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:

```csharp
[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?

 Install `Selenium.WebDriver` 3.x, which still has the class. A lambda that finds the element and returns it when it is displayed and enabled, or null otherwise. `Thread.Sleep` followed by `Click()`.

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[#](https://testingbot.com#conditions-of-your-own)

A lambda can wait for anything you can compute. Click "Add a box!" three times and wait for all three:

```csharp
[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:

```csharp
[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](https://testingbot.com/resources/courses/flaky-tests) 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.

[Previous · Chapter 2 Set up .NET, Selenium and NUnit](https://testingbot.com/resources/courses/selenium-csharp/setup-and-first-test) [Next · Chapter 4 NUnit fixtures, attributes and [TestCase] ](https://testingbot.com/resources/courses/selenium-csharp/nunit-fixtures-and-attributes)

On this page

1. [The By strategies](https://testingbot.com#the-by-strategies)
2. [Many elements, or none](https://testingbot.com#many-elements-or-none)
3. [Dropdowns](https://testingbot.com#dropdowns)
4. [Waits: the failure](https://testingbot.com#waits-the-failure)
5. [WebDriverWait with a lambda](https://testingbot.com#webdriverwait-with-a-lambda)
6. [Where is ExpectedConditions?](https://testingbot.com#where-is-expectedconditions)
7. [Conditions of your own](https://testingbot.com#conditions-of-your-own)

Certification

Earn the free, resume-worthy TestingBot Selenium C# Certification for this course.

[How it works](https://testingbot.com/resources/courses/selenium-csharp/certification)
