Verify login button using absolute and relative XPath
Preconditions (2)
✅ Expected Result: The login button is found and visible using both absolute and relative XPath locators
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 XPathTest { 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("https://example.com/login"); // Absolute XPath example (not recommended for real tests) String absoluteXPath = "/html/body/div[2]/div/form/button"; WebElement loginButtonAbsolute = wait.until( ExpectedConditions.visibilityOfElementLocated(By.xpath(absoluteXPath)) ); assert loginButtonAbsolute.isDisplayed() : "Login button not visible using absolute XPath"; // Relative XPath example (recommended) String relativeXPath = "//button[@id='loginBtn']"; WebElement loginButtonRelative = wait.until( ExpectedConditions.visibilityOfElementLocated(By.xpath(relativeXPath)) ); assert loginButtonRelative.isDisplayed() : "Login button not visible using relative XPath"; System.out.println("Test passed: Login button found using both XPath types."); } finally { driver.quit(); } } }
This code opens the login page in Chrome browser.
It waits explicitly for the login button to be visible using two XPath locators:
Assertions check if the button is visible for both locators.
Finally, the browser closes to clean up.
Now add data-driven testing with 3 different XPath locators for the login button and verify visibility for each.
<div>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>//ul/li[2] select?/html/body/div/button[@id='loginBtn']Pass the test and this pattern moves unknown