如何使用Selenium根據索引在XPath節點集中選擇指定的節點?


我們可以使用Selenium webdriver根據索引在XPath節點集中選擇特定的節點。我們可以藉助其包含在[]中的索引號來提及特定節點。

讓我們看一下下面HTML程式碼中具有子元素的元素。具有標籤名ul的元素具有多個標籤名為li的子元素。如果我們想識別具有文字“軟體質量管理”的父元素的第二個子元素,則帶有節點索引的XPath表示式應為//ul[@class='list']li[2]

識別父元素ul的第二個子元素的XPath表示式也可以藉助XPath中的position()函式建立。為了精確找到第二個元素,我們必須將position()=2附加到XPath。因此,完整的XPath表示式應為//ul[@class='list']/li[position()=2]

示例

使用帶有索引的XPath的程式碼實現

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ElementIndex{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/tutorials_writing.htm");
      // identify element with xpath having index
      WebElement t = driver.findElement(By.xpath("//ul[@class='list']/li[2]"));
      //getText to get element text
      System.out.println("The element is: " + t.getText());
      driver.close();
   }
}

使用帶有position()的XPath的程式碼實現

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ElementPosition{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/tutorials_writing.htm");
      // identify element with xpath having position()
      WebElement t = driver.findElement(By.xpath("//ul[@class='list']/li[position()=2]"));
      //getText to get element text
      System.out.println("The element is: " + t.getText());
      driver.close();
   }
}

輸出

更新於:2020年10月26日

6000+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.