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 >>
Please Follow Step 1: Read XPath Question >>Step 2: Check HTML Source Code >>Step3: 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) {
        // Set up the web driver
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        // Navigate to a website
        driver.get("https://www.example.com");

        // Select the second 
  • element in the list WebElement element = driver.findElement(By.xpath("(//li)[2]")); // Do something with the selected element System.out.println(element.getText()); // Close the web driver driver.quit(); } }
  • We would love to hear your thoughts, suggestions, concerns or problems with anything so we can improve. Request you to please use Social Media button in Right Side for this website growth.