There is a problem in using the locators mentioned in earlier articles, which is that many site will not have the locator you were planning to use and some site use alphanumeric as the locator value, these alphanumeric are dynamic and changes every few intervals this will make useless for a long run. There is a way to avoid this problem by using Xpath.
What is Xpath
XPath also called as XML Path is a language to query XML documents. It is an important strategy to locate elements in Selenium. Xpath Query and Scripts are written to locate elements in Webpage.
Xpath and CSS are the most stable selector which are used even in Industry as they are reliable locator. You can create your own Xpath and can also customize it. For an element you can have more than one Xpath.
Getting Xpath
All the popular browser have an inbuilt Xpath and CSS engine, you can create your Xpath and validate them with your Browser's Developer mode.
Open the Developer tool's Inspect, select the element you want to listen and hover above the page source and right click to view the list of open then select the copy menu.
In the menu, click the copy Xpath. This will copy the Xpath to your clipboard.
We will so in-dept about the Xpath and CSS on our later article.
Code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Xpath {
public static void main(String args[]) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","D:\\Software\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://github.com/login");
driver.findElement(By.xpath("//*[@id='login_field']")).sendKeys("prathapdom@gmail.com");
//Added a timer for 2 sec which let us see our UI movements
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("password");
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id='login']/form/div[3]/input[7]")).click();
}
}