We use findElement with XPath to locate a specific element on a web page when other simpler locators are not enough.
findElement by xpath in Selenium Java
WebElement element = driver.findElement(By.xpath("xpath_expression"));The xpath_expression is a string that describes the path to the element.
This method returns the first matching element or throws an exception if none found.
WebElement loginButton = driver.findElement(By.xpath("//button[@id='login']"));WebElement firstLink = driver.findElement(By.xpath("//a[text()='Home']"));WebElement inputField = driver.findElement(By.xpath("//input[@type='text' and @name='username']"));This test script opens a login page, finds username and password input fields and the login button using XPath, fills in credentials, clicks the button, and prints a success message.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FindElementByXPathExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/login"); WebElement usernameInput = driver.findElement(By.xpath("//input[@name='username']")); usernameInput.sendKeys("testuser"); WebElement passwordInput = driver.findElement(By.xpath("//input[@name='password']")); passwordInput.sendKeys("password123"); WebElement loginButton = driver.findElement(By.xpath("//button[text()='Login']")); loginButton.click(); System.out.println("Login button clicked successfully."); } catch (Exception e) { System.out.println("Element not found or error occurred: " + e.getMessage()); } finally { driver.quit(); } } }
Always use clear and stable XPath expressions to avoid flaky tests.
If findElement does not find the element, it throws NoSuchElementException.
Use browser DevTools to test XPath expressions before using them in code.
findElement by xpath helps locate web elements when simple locators are not enough.
XPath expressions can find elements by attributes, text, or position.
Always handle exceptions to keep tests stable.
Practice
findElement(By.xpath("//button[@id='submit']")) do?Solution
Step 1: Understand the method purpose
The methodfindElementlocates a single web element matching the given locator.Step 2: Analyze the XPath expression
The XPath//button[@id='submit']selects the first<button>element with attributeid='submit'.Final Answer:
Finds the first button element with id 'submit' on the page -> Option AQuick Check:
findElement + XPath = single matching element [OK]
- Confusing findElement with findElements
- Thinking it clicks or deletes element
- Assuming it returns multiple elements
Solution
Step 1: Check method call syntax
The correct method call isdriver.findElement(By.xpath("xpath_string"))with double quotes around the XPath string.Step 2: Validate each option
driver.findElement(By.xpath("//input[@name='username']")); uses correct syntax with double quotes and proper method call. driver.findElement(By.xpath=//input[@name='username']); uses invalid assignment syntax. driver.findElement(By.xpath('//input[@name='username']')); uses single quotes inside double quotes incorrectly. driver.findElement(By.xpath("input[@name='username']")); misses the leading '//' in XPath.Final Answer:
driver.findElement(By.xpath("//input[@name='username']")); -> Option CQuick Check:
Correct method call with By.xpath and string [OK]
- Using assignment '=' instead of method argument
- Mixing single and double quotes incorrectly
- Omitting '//' in XPath expression
WebElement element = driver.findElement(By.xpath("//div[@class='menu']/ul/li[2]"));
System.out.println(element.getText());
Assuming the HTML is:<div class='menu'>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>Solution
Step 1: Understand the XPath expression
The XPath//div[@class='menu']/ul/li[2]selects the second<li>child inside the<ul>within thedivwith class 'menu'.Step 2: Match XPath to HTML content
The second<li>inside the list isAbout. Soelement.getText()will print "About".Final Answer:
About -> Option DQuick Check:
XPath li[2] = second list item text [OK]
- Confusing index starting at 0 instead of 1
- Assuming XPath returns all matching elements
- Ignoring the class attribute filter
NoSuchElementException. What is the likely error?
WebElement button = driver.findElement(By.xpath("//button[text()='Submit']"));
button.click();
The HTML is:
<button id='submitBtn'>Submit</button>
Solution
Step 1: Check XPath correctness
The XPath//button[text()='Submit']matches the button text exactly, which is correct here.Step 2: Consider common Selenium issues
If the element is inside an iframe, Selenium cannot find it unless switched to that iframe first. This causesNoSuchElementException.Final Answer:
The button element is inside an iframe and not switched to -> Option AQuick Check:
NoSuchElementException often means iframe switch missing [OK]
- Assuming XPath text match is case-insensitive
- Ignoring iframe context
- Thinking disabled buttons cause NoSuchElementException
name='email' or placeholder='Email'. Which XPath expression should you use with findElement?Solution
Step 1: Understand the requirement
You want to find an input element that matches either condition: name='email' OR placeholder='Email'.Step 2: Analyze XPath options
//input[@name='email' or @placeholder='Email'] uses the correct XPath OR operatororbetween attribute checks. //input[@name='email' and @placeholder='Email'] usesandwhich requires both attributes. //input[contains(@name, 'email') or contains(@placeholder, 'Email')] usescontainswhich is broader but acceptable, but the question asks exact match. //input[@name='email' | @placeholder='Email'] uses invalid XPath syntax with|inside predicate.Final Answer:
//input[@name='email' or @placeholder='Email'] -> Option BQuick Check:
Use 'or' inside XPath predicate for either condition [OK]
- Using 'and' instead of 'or' for either condition
- Using invalid XPath operators like '|' inside predicates
- Confusing contains() with exact match
Ready to prove it?
Pass the test and this pattern moves unknown
