使用 XPath 在 Selenium 中查找元素和查找元素集
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();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify elements with findElements xpath
List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li"));
//count of list of matching elements
int s = p.size();
//identify element with xpath
WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]"));
System.out.println("Element text is: "+ m.getText());
driver.quit();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP