使用 Selenium WebDriver 查找元素?
借助 findElements 方法,我们可以用 Selenium webdriver 查找元素。这适用于 id、class、name、链接文本、部分链接文本、CSS、xpath 和标记名称等定位器。
findElements 方法返回一个元素列表,该列表与作为该方法的参数传递的定位器(使用 By 对象)匹配。要计算列表返回的元素数量,请使用尺寸方法。如果没有匹配的元素,则返回一个空列表。
下图显示了 findElements 可用的方法列表。

范例
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;
import java.util.List;
public class FindElmnts{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
//identify elements with anchor tagname
List e = driver.findElements(By.tagName("a"));
//count matching elements with size
int s = e.size();
System.out.println("Number of matching elements: " + s);
driver.quit();
}
}输出

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