XPath with attributes helps you find specific elements on a web page by looking at their properties. This makes your tests more accurate and reliable.
0
0
XPath with attributes in Selenium Java
Introduction
When you want to click a button with a unique id or class.
When you need to check if a specific input field is present by its name attribute.
When you want to verify a link with a certain href value.
When elements have similar tags but different attributes to distinguish them.
When you want to find elements dynamically without relying on fixed positions.
Syntax
Selenium Java
//tagName[@attributeName='attributeValue']Use double slashes // to search anywhere in the page.
Attributes are inside square brackets with @ before the attribute name.
Examples
Selects an input element with id equal to 'username'.
Selenium Java
//input[@id='username']
Selects a button element with class 'submit-btn'.
Selenium Java
//button[@class='submit-btn']Selects a link with the exact href 'https://example.com'.
Selenium Java
//a[@href='https://example.com']Selects a div element with a custom attribute 'data-test' equal to 'login-form'.
Selenium Java
//div[@data-test='login-form']Sample Program
This test opens a login page, finds elements using XPath with attributes, enters credentials, clicks login, and checks if login succeeded by page title.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class XPathWithAttributesTest { 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"); // Find username input by id attribute WebElement usernameInput = driver.findElement(By.xpath("//input[@id='username']")); usernameInput.sendKeys("testuser"); // Find password input by name attribute WebElement passwordInput = driver.findElement(By.xpath("//input[@name='password']")); passwordInput.sendKeys("password123"); // Find login button by class attribute and click WebElement loginButton = driver.findElement(By.xpath("//button[@class='login-btn']")); loginButton.click(); // Simple check: verify page title contains 'Dashboard' String title = driver.getTitle(); if (title.contains("Dashboard")) { System.out.println("Test Passed: Logged in successfully."); } else { System.out.println("Test Failed: Login unsuccessful."); } } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Always use unique attributes to avoid selecting wrong elements.
Use browser DevTools to test XPath expressions before using them in code.
Remember to handle exceptions if elements are not found to avoid test crashes.
Summary
XPath with attributes helps find elements by their properties.
Use syntax like //tag[@attr='value'] for precise selection.
Testing XPath in browser tools saves time and errors.