Q5 of 37 · Selenium
What is a WebElement and how do you locate one?
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:
Single vs many —
findElementreturns one and throwsNoSuchElementExceptionif missing;findElementsreturns a (possibly empty) list. If existence is uncertain, use the plural and check size.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();