Testing / Selenium Interview questions
How do you use the By class in Selenium?
By is a static factory class whose methods each build a locator strategy that findElement() or findElements() can then use to search the DOM.
WebElement login = driver.findElement(By.id("login-btn")); List<WebElement> rows = driver.findElements(By.cssSelector("table tr")); WebElement link = driver.findElement(By.linkText("Sign up"));
Selenium 4 added relative locators built on top of By, letting you find elements positioned near another element - By.id("password") combined with RelativeLocator.with(By.tagName("input")).below(usernameField), for example - which is useful when an element has no stable id or text of its own but sits in a predictable visual position relative to one that does.
More Related questions...