XPath Practice: Mastering XPath Expressions for Effective Web Automation using Index.

Test Your Skills with this Fun and Interactive Game


Home->Practice 8

Next
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 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

XPath O/P

Enter XPath Input 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.