findElement by name in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class FindElementByNameTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("http://example.com/login"); // Wait until the login button is visible WebElement loginButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("loginButton"))); // Assert the button is displayed if (!loginButton.isDisplayed()) { throw new AssertionError("Login button is not displayed"); } // Assert the button is enabled if (!loginButton.isEnabled()) { throw new AssertionError("Login button is not enabled"); } // Click the login button loginButton.click(); System.out.println("Test passed: Login button found and clicked successfully."); } catch (Exception e) { System.out.println("Test failed: " + e.getMessage()); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it sets up the ChromeDriver and opens the browser to the login page URL.
It uses an explicit wait to wait until the login button with the name='loginButton' is visible on the page.
Then it checks if the button is displayed and enabled before clicking it. If either check fails, it throws an assertion error.
Finally, it clicks the button and prints a success message. The browser is closed in the finally block to ensure cleanup.
This approach follows best practices by using explicit waits, proper locators, and error handling.
Now add data-driven testing with 3 different name attributes for buttons to verify each is clickable.
Practice
findElement(By.name("username")) do in a test script?Solution
Step 1: Understand the method purpose
The methodfindElement(By.name("username"))searches for a single element with thenameattribute equal to "username".Step 2: Differentiate from other locators
This method does not search by tag, id, or class, only by thenameattribute.Final Answer:
It finds the first web element with the attribute name="username". -> Option BQuick Check:
findElement(By.name) = finds element by name attribute [OK]
- Confusing name with id or class attributes
- Thinking it finds multiple elements instead of one
- Assuming it performs a click automatically
Solution
Step 1: Identify the correct locator method
To find an element by its name attribute, the correct method isBy.name("email").Step 2: Verify syntax correctness
The syntaxdriver.findElement(By.name("email"));is valid and correctly uses the name locator.Final Answer:
driver.findElement(By.name("email")); -> Option CQuick Check:
Use By.name for name attribute [OK]
- Using By.id or By.className instead of By.name
- Missing quotes around the name value
- Using incorrect method names
<input name="search">?
WebElement element = driver.findElement(By.name("search"));
System.out.println(element.getTagName());Solution
Step 1: Locate element by name attribute
The code finds the element withname="search", which is aninputtag.Step 2: Print the tag name of the found element
The methodgetTagName()returns the tag name of the element, which is "input".Final Answer:
It prints "input" to the console. -> Option AQuick Check:
getTagName() returns tag name [OK]
- Expecting getTagName() to return attribute value
- Assuming element not found causes print output
- Confusing attribute name with tag name
WebElement element = driver.findElement(By.name("submitBtn"));
element.click();
Assume the page does not have any element with name="submitBtn".Solution
Step 1: Understand findElement behavior when element missing
If no element matches the locator,findElementthrowsNoSuchElementException.Step 2: Check what happens before click()
The exception occurs beforeclick()is called, so click is never reached.Final Answer:
NoSuchElementException will be thrown at findElement. -> Option DQuick Check:
Missing element causes NoSuchElementException [OK]
- Expecting null instead of exception
- Thinking click() causes NullPointerException
- Assuming silent failure without error
Solution
Step 1: Understand iframe context in Selenium
Elements inside iframes require switching the driver's context to that iframe before locating elements inside it.Step 2: Apply correct order of operations
First switch to the iframe, then usefindElement(By.name("userEmail"))to locate the element inside it.Final Answer:
Switch to iframe first, then use driver.findElement(By.name("userEmail")). -> Option AQuick Check:
Switch to iframe before locating inside it [OK]
- Trying to find element inside iframe without switching
- Using wrong locator like id instead of name
- Switching to iframe after locating element
Ready to prove it?
Pass the test and this pattern moves unknown
