XPath Selenium WebDriver Java Guide
XPath Selenium WebDriver Java Guide
1. Introduction to XPath
XPath is used in Selenium to locate elements in the DOM of web pages. It?s especially useful for elements without
unique identifiers.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
driver.get("https://example.com");
// Examples here...
driver.get("https://www.amazon.in/");
driver.findElement(By.xpath("//input[@id='twotabsearchtextbox']")).sendKeys("iPhone");
driver.findElement(By.xpath("//input[@id='nav-search-submit-button']")).click();
driver.findElement(By.xpath("(//span[contains(text(),'iPhone')])[1]")).click();
4. Facebook.com ? Login
driver.get("https://www.facebook.com/");
driver.findElement(By.xpath("//input[@id='email']")).sendKeys("testuser");
XPath in Selenium WebDriver (Java) - Beginner to Expert
driver.findElement(By.xpath("//input[@id='pass']")).sendKeys("dummyPassword");
driver.findElement(By.xpath("//button[@name='login']")).click();
driver.get("https://en.wikipedia.org/wiki/Selenium_(software)");
driver.get("https://the-internet.herokuapp.com/login");
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("tomsmith");
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("SuperSecretPassword!");
driver.findElement(By.xpath("//button[@type='submit']")).click();
driver.get("https://www.youtube.com/");
driver.findElement(By.xpath("//input[@id='search']")).sendKeys("XPath Tutorial");
driver.findElement(By.xpath("//button[@id='search-icon-legacy']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//a[@id='video-title'])[1]")).click();
button.click();