Q5 of 37 · Selenium

What is a WebElement and how do you locate one?

SeleniumJuniorseleniumwebelementlocatorsfundamentals

Short answer

Short answer: A WebElement is a Selenium handle to a DOM element on the current page. You locate one with `driver.findElement(By.<strategy>(value))` using a By locator — id, css, xpath, name, link text, class name, tag name.

Detail

A WebElement is the Selenium representation of a DOM node. Once you have one, you can call click(), sendKeys(), getText(), getAttribute(), isDisplayed(), and so on — the operations you'd want to perform on a real-page element.

You don't construct WebElements directly. You ask the driver to locate one by passing a By locator:

  • By.id("submit") — most reliable when present.
  • By.cssSelector("[data-test=submit]") — preferred for production code.
  • By.xpath("//button[text()='Submit']") — fallback for text/attribute combinations CSS can't express.
  • By.name("email"), By.className("error"), By.linkText("Sign in"), By.partialLinkText("Sign"), By.tagName("h1").

Two patterns matter:

  1. Single vs manyfindElement returns one and throws NoSuchElementException if missing; findElements returns a (possibly empty) list. If existence is uncertain, use the plural and check size.

  2. Scope a search — calling element.findElement(By.cssSelector(".error")) searches within that element, not the whole document. Useful when the same selector exists in multiple regions.

In real test code you almost always wrap the lookup in an explicit wait so the element has time to render before you act on it.

// EXAMPLE

WebElement email = driver.findElement(By.cssSelector("[data-test=email]"));
email.sendKeys("alice@example.com");

// Scoped search — find error within the form, not anywhere
WebElement form = driver.findElement(By.id("login-form"));
List<WebElement> errors = form.findElements(By.cssSelector(".error"));
boolean hasError = !errors.isEmpty();

// WHAT INTERVIEWERS LOOK FOR

Knowing the By strategies, when each is appropriate, and the singular/plural distinction. Bonus for mentioning scoped searches off an existing element.

// COMMON PITFALL

Calling findElement on an element that may not exist and not handling NoSuchElementException — or relying on findElements size without realising the call doesn't wait.