XPath in Selenium WebDriver (Java) - Beginner to Expert
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.
2. Setup for Selenium Java
Import necessary packages and set up your driver:
import [Link];
import [Link];
import [Link];
import [Link];
public class XPathExamples {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Examples here...
3. [Link] ? Search iPhone
[Link]("[Link]
[Link]([Link]("//input[@id='twotabsearchtextbox']")).sendKeys("iPhone");
[Link]([Link]("//input[@id='nav-search-submit-button']")).click();
[Link]([Link]("(//span[contains(text(),'iPhone')])[1]")).click();
4. [Link] ? Login
[Link]("[Link]
[Link]([Link]("//input[@id='email']")).sendKeys("testuser");
XPath in Selenium WebDriver (Java) - Beginner to Expert
[Link]([Link]("//input[@id='pass']")).sendKeys("dummyPassword");
[Link]([Link]("//button[@name='login']")).click();
5. [Link] ? Extract Title
[Link]("[Link]
WebElement heading = [Link]([Link]("//h1[@id='firstHeading']"));
[Link]("Page title: " + [Link]());
6. Demo Login Page ? Form Submit
[Link]("[Link]
[Link]([Link]("//input[@id='username']")).sendKeys("tomsmith");
[Link]([Link]("//input[@id='password']")).sendKeys("SuperSecretPassword!");
[Link]([Link]("//button[@type='submit']")).click();
7. [Link] ? Search Video
[Link]("[Link]
[Link]([Link]("//input[@id='search']")).sendKeys("XPath Tutorial");
[Link]([Link]("//button[@id='search-icon-legacy']")).click();
[Link](2000);
[Link]([Link]("(//a[@id='video-title'])[1]")).click();
8. Wait for Dynamic Elements
WebDriverWait wait = new WebDriverWait(driver, [Link](10));
WebElement button = [Link]([Link]([Link]("//button[text()='Submit']")));
[Link]();