We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Use By.xpath to locate elements by path and attributes.
XPath is a query language used to find nodes in XML documents. Because HTML is XML-like, Selenium can use XPath to locate elements on a page.
XPath is appropriate when:
//button[text()='Submit']).What it does
Starts from the root element / and walks through every level of the DOM. Uses exact hierarchy and often positions like [1].
What it does
Starts with // which means “search anywhere in the document”. Targets elements by tag, attributes, and optional conditions.
contains().This form's structure is specifically designed to practice absolute and relative XPath queries.
123456789101112131415WebElement firstNameInput = driver.findElement(By.xpath("//form/div[1]/input"));
firstNameInput.clear();
firstNameInput.sendKeys("John");
WebElement lastNameInput = driver.findElement(By.xpath("//input[@name='lname']"));
lastNameInput.clear();
lastNameInput.sendKeys("Doe");
WebElement companyInput = driver.findElement(By.xpath("//input[@id='company']"));
companyInput.sendKeys("Selenium Corp");
WebElement newsletterCheckbox = driver.findElement(By.xpath("//input[contains(@name,'news')]"));
newsletterCheckbox.click();
driver.quit();<div> inside the <form>, then its <input> child. This behaves like an absolute-style path relative to the form and is fragile if the layout changes.<input> anywhere with name='lname'. This is more stable and recommended.id. Uses the pattern //tag[@id='value'] which is very reliable when IDs are unique.contains() function to match inputs where the name attribute contains "news" (e.g. "newsletter"). Very useful for partial attribute matching.Use // over absolute paths starting at /html/.... Your tests will survive small layout changes much better.
Use clear attribute-based XPaths like //input[@id='company'] instead of deeply nested positional paths.
contains(), starts-with(), etc. are powerful, but don’t overuse them—combine them with specific tags/attributes to keep locators stable.