在 Selenium 中通过 XPath 查找元素和 FindElements

seleniumautomation testingtesting tools更新于 2026/1/24 3:22:17

findElement(By.xpath) 方法用于识别与作为参数传递给此方法的 xpath 定位器匹配的元素。findElements(By.xpath) 方法用于识别与作为参数传递给该方法的 xpath 定位器匹配的元素集合。

findElement(By.xpath) 方法返回一个 Web 元素,而 findElements(By.xpath) 方法返回一个 Web 元素列表。如果没有匹配的元素,findElement(By.xpath) 方法会抛出异常。如果 findElements(By.xpath) 方法没有获得匹配的元素,则返回一个空的元素列表。

让我们尝试确定 ul 标签的子元素数量以及 ul 的第一个子元素(li[1] 包含文本"选定的阅读")。

语法

List<WebElement> n =
driver.findElements(By.xpath("//ul[@class=' toc reading']/li"));
WebElement m =driver.findElement(By.xpath("//ul[@class=' toc reading']/li[1]"));

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class XpathFindElment{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 使用 findElements xpath 识别元素
      List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li"));
      //匹配元素列表的数量
      int s = p.size();
      //使用 xpath 识别元素
      WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]"));
      System.out.println("Element text is: "+ m.getText());

      driver.quit();
   }
}

输出


相关文章