Selenium Java to locate a web element using the following and preceding XPath axes
KW.java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class KW
{
    public static void main(String[] args) 
    {   
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "/home/kodingwindow/drivers/chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.navigate().to("https://kodingwindow.com/testapp/");
        
        //sending username
        driver.findElement(By.xpath("//*[@name='password']//preceding::input[@type='text']")).sendKeys("kodingwindow");
        
        //sending password
        driver.findElement(By.xpath("//*[@name='username']//following::input[@type='password']")).sendKeys("kodingwindow");
        
        //clicking login button
        driver.findElement(By.xpath("//*[@name='login']//self::button")).click();
        driver.close();
    }
}
Advertisement