Selenium WebDriver allows us to automate web applications by interacting with web elements. One common way to find these elements is using their name attribute through By.name().
π What is the name Attribute in HTML?
The name attribute is used to reference form elements during submission. Although not required to be unique like id, it's often used consistently in web forms.
<input type="text" name="username" />
✅ When to Use By.name()?
- ✅ When elements have a descriptive and consistent
nameattribute - ✅ When
idis missing or dynamic - ✅ Works well with forms, especially login, signup, search fields
π Syntax in Java
driver.findElement(By.name("element_name"));
π‘ HTML Example
Below is a simple HTML login form using the name attribute:
<form>
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="login" value="Login" />
</form>
π» Selenium + Java Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LoginByName {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
// Locate elements using name
WebElement username = driver.findElement(By.name("username"));
WebElement password = driver.findElement(By.name("password"));
WebElement loginBtn = driver.findElement(By.name("login"));
// Interact with them
username.sendKeys("testuser");
password.sendKeys("testpass");
loginBtn.click();
driver.quit();
}
}
✅ Best Practices
| Tip | Why? |
|---|---|
Use By.name() if id is missing |
name is still a reliable and readable option |
Use WebDriverWait for dynamic elements |
Ensure elements are loaded before accessing |
| Validate uniqueness | Ensure that only one element uses the name to avoid ambiguity |
π Using Wait with By.name()
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("username")));
⚠️ Common Issues
| Issue | Solution |
|---|---|
NoSuchElementException |
Element not loaded yet → Use waits |
| Multiple elements with same name | Use findElements() to handle multiple matches |
name not present |
Use alternative locators like id, xpath |
π Example: Handle Multiple Elements
List<WebElement> options = driver.findElements(By.name("gender"));
options.get(0).click(); // Click on the first gender option
π Summary
By.name()is a simple and readable way to locate elements in Selenium.- Works best with forms and when
idis not available.- Always verify that the
nameis unique if usingfindElement().
π What's Next?
Explore more Selenium locators: