XPath Index: Enhance your skills by practicing XPath Index syntax with our given sample HTML codes and interactive exercises, designed to help you master selecting elements in HTML and XML documents.

Boost Your Skills: Practice XPath Index Syntax with easy Exercises.


Home → Practice 8

Next Exercise >>
Step 1: Read XPath Question → Step 2: Check HTML Source Code → Step 3: Enter XPath Syntax in O/P Box

XPath Exercise 8

Q1. Find First Span using Index

Q2. Find Second Span using Index

Q3. Find First Heading using Index

Q4. Find Second Heading using Index

Q5. Find First Para using Index

Q6. Find Second Para using Index

Q7. Find Third Para using Index

Q8. Find Fourth Para using Index

HTML Source Document

<span class="sub-text">Span 1</span>
<span class="sub-text">Span 2</span>

<h1 class="h1">Heading 1</h1>
<h1 class="h1">Heading 2</h1>

<p>Para 1</p>
<p>Para 2</p>
<p>Para 3</p>
<p>Para 4</p>
      

XPath O/P Box

Enter XPath Syntax here:

XPath Tips and Syntax For This Page Exercise:

Using index

//span[2]
    

The index function in XPath can be used to select elements based on their position in a list of similar elements.

e.g.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class IndexExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        WebElement element = driver.findElement(By.xpath("(//li)[2]"));
        System.out.println(element.getText());
        driver.quit();
    }
}
    
We would love to hear your thoughts, suggestions, concerns or problems with anything so we can improve. Please use the Social Media button on the right side to help this website grow.