Selenium Webelement Methods Commands

Advertisement

Selenium WebElement & Browser Commands

Almost everything you do in Selenium goes through two interfaces: WebDriver (the browser) and WebElement (one element on the page). This reference lists the commands you'll actually use in Selenium 4, grouped by job, with the differences interviewers ask about — get() vs navigate(), findElement() vs findElements(), getText() vs attribute methods, and close() vs quit().

The Interface Hierarchy

SearchContext                         findElement(), findElements()
   ├── WebDriver                      the browser session
   │      └── RemoteWebDriver          (implements WebDriver, JavascriptExecutor, TakesScreenshot, …)
   │             └── ChromiumDriver → ChromeDriver, EdgeDriver
   │             └── FirefoxDriver, SafariDriver
   └── WebElement                     one element (also a SearchContext)

SearchContext is the top interface, with just findElement() and findElements(). Because WebElement is also a SearchContext, you can search inside an element: form.findElement(By.name("email")). WebDriver driver = new ChromeDriver(); works because ChromeDriver implements the WebDriver interface — the reason the same test code runs on any browser.

WebDriver also has nested interfaces reached through methods: navigate() → Navigation, manage() → Options (with window() → Window and timeouts() → Timeouts), and switchTo() → TargetLocator.

WebDriver Commands

Opening and navigating

driver.get("https://www.saucedemo.com/");          // open a URL
driver.navigate().to("https://www.selenium.dev/"); // open a URL, keeping history
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

get() vs navigate().to()

Both open a URL and, by default, both wait for the page's load event (controlled by the page load strategy). The practical difference is the API: get() is the direct way to open a page; navigate() returns the Navigation interface, which adds back(), forward() and refresh(). navigate().to() also accepts a URL object.

Analogy: get() is typing a URL and pressing Enter; navigate() is the browser's toolbar — it can also go back, forward and reload.

Many older tutorials claim navigate().to() doesn't wait for the page to load — in Selenium 4 both wait the same way.

Page information

driver.getTitle();          // page title
driver.getCurrentUrl();     // current URL — assert redirects
driver.getPageSource();     // full HTML — useful for debugging, not for assertions

Windows and sizes

driver.manage().window().maximize();
driver.manage().window().minimize();
driver.manage().window().fullscreen();
driver.manage().window().setSize(new Dimension(1920, 1080));   // fixed size for consistent CI runs

String parent = driver.getWindowHandle();                        // current window
Set<String> all = driver.getWindowHandles();                     // every window/tab
driver.switchTo().window(parent);
driver.switchTo().newWindow(WindowType.TAB);                     // Selenium 4

More on windows, frames and alerts: Alerts, Frames & Windows.

Timeouts

driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(10));
driver.manage().timeouts().implicitlyWait(Duration.ZERO);        // keep 0; use explicit waits

Ending the session: close() vs quit()

  close() quit()
Closes The current window only Every window
Session Stays open (if other windows remain) Ends; the driver process exits
Use Closing a pop-up or child tab End of every test, in @AfterMethod(alwaysRun = true)

After close(), switch to a remaining window before the next command. Forgetting quit() leaves browser and driver processes running — a common cause of CI agents running out of memory.

Finding Elements

  findElement() findElements()
Returns The first matching WebElement List<WebElement> of all matches
No match Throws NoSuchElementException Returns an empty list
Use for Interacting with one element Counting, looping, checking absence
WebElement username = driver.findElement(By.id("user-name"));
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Links on the page: " + links.size());

boolean errorShown = !driver.findElements(By.cssSelector("[data-test='error']")).isEmpty();

All locator strategies: Selenium Locators Cheat Sheet.

WebElement Commands

Interacting

WebElement field = driver.findElement(By.id("user-name"));
field.clear();                                   // empty a text field
field.sendKeys("standard_user");                 // type
field.sendKeys(Keys.TAB);                        // special keys
driver.findElement(By.id("login-button")).click();
driver.findElement(By.id("user-name")).submit(); // submits the element's enclosing form

submit() works on any element inside a <form> and submits that form. Clicking the real submit button is usually better, because it triggers the same JavaScript a user would.

Reading content ⭐

Method Returns Example
getText() Visible text Labels, messages, headings — empty for input fields
getDomProperty("value") Live DOM property What's currently typed in an input; checked
getDomAttribute("href") Attribute as written in the HTML placeholder, type, data-test
getAttribute("value") Property or attribute (mixed behaviour) Deprecated since Selenium 4.27 — still works
getCssValue("color") Computed CSS value rgba(226, 35, 26, 1)
getTagName() Tag name input
getAccessibleName() / getAriaRole() Accessibility info Accessibility checks

State

element.isDisplayed();   // visible on the page?
element.isEnabled();     // not disabled?
element.isSelected();    // checkbox, radio or option selected?

These only work on elements that exist: isDisplayed() on a missing element throws NoSuchElementException — check absence with findElements(...).isEmpty(). A single state check isn't a wait; use ExpectedConditions for anything that changes. More: Selenium Waits.

Position and size

Point location = element.getLocation();          // location.getX(), location.getY()
Dimension size = element.getSize();              // size.getWidth(), size.getHeight()
Rectangle rect = element.getRect();              // position and size together

Useful for layout checks and for calculating offsets, for example when dragging a slider with the Actions class.

Screenshots and shadow DOM

File full = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);   // whole viewport
File just = element.getScreenshotAs(OutputType.FILE);                      // one element
SearchContext shadow = host.getShadowRoot();                               // inside a shadow DOM

A Complete Example

WebDriver driver = new ChromeDriver();                       // Selenium Manager finds the driver
try {
    driver.manage().window().setSize(new Dimension(1366, 768));
    driver.get("https://www.saucedemo.com/");
    Assert.assertEquals(driver.getTitle(), "Swag Labs");

    WebElement user = driver.findElement(By.id("user-name"));
    Assert.assertEquals(user.getDomAttribute("placeholder"), "Username");
    user.sendKeys("standard_user");
    Assert.assertEquals(user.getDomProperty("value"), "standard_user");

    driver.findElement(By.id("password")).sendKeys("secret_sauce");
    driver.findElement(By.id("login-button")).click();

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.urlContains("inventory"));
    System.out.println("Products shown: " + driver.findElements(By.cssSelector(".inventory_item")).size());
} finally {
    driver.quit();
}

Since Selenium 4.6, Selenium Manager downloads the right driver automatically — no System.setProperty("webdriver.chrome.driver", …) needed. See each of these commands travel from your test to the browser in the Selenium WebDriver Visualizer.

From Real Projects

I've used Selenium WebDriver with Java and TestNG in Eclipse on Canolog, an automotive dealership management system, and on Testsigma. The practical skills behind this page — identifying elements by id, class name and XPath, handling the browser, and structuring scripts in POM classes — were part of my daily automation work, along with running scripts on Chrome and Firefox. Practise each exercise until you can write it without looking anything up. Know which commands return values and which only act — it avoids many small mistakes.

📚 Official documentation: Selenium documentation

FAQs

What methods does SearchContext provide?

findElement() and findElements() — inherited by both WebDriver and WebElement.

What is the difference between get() and navigate().to()?

Both open a URL and wait for the page to load by default. navigate() belongs to the Navigation interface, which also provides back, forward and refresh.

What is the difference between findElement() and findElements()?

findElement() returns the first match or throws NoSuchElementException; findElements() returns a list, empty if nothing matches.

Why does getText() return an empty string for an input?

Input values aren't text content. Use getDomProperty("value").

driver.findElements(By.tagName("a")).size().

What is the difference between close() and quit()?

close() closes the current window; quit() closes all windows and ends the WebDriver session.