This Java Selenium code opens a login page and finds the username input field using both absolute and relative XPath. It prints the 'name' attribute of the found elements.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPathExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
// Using absolute XPath
WebElement absoluteElement = driver.findElement(By.xpath("/html/body/div[1]/form/input[1]"));
String absoluteValue = absoluteElement.getAttribute("name");
// Using relative XPath
WebElement relativeElement = driver.findElement(By.xpath("//input[@name='username']"));
String relativeValue = relativeElement.getAttribute("name");
System.out.println("Absolute XPath found element with name: " + absoluteValue);
System.out.println("Relative XPath found element with name: " + relativeValue);
driver.quit();
}
}